Problem with colliding a player with a trigger and making the player go back to the main menu - collision

I made a trigger where the player collides and it goes to the main menu (scene 0) and it just wont work. I'm using unity with c#:
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneTransition : MonoBehaviour
{
public string SceneToLoad;
public void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player")) ;
{
SceneManager.LoadScene(SceneToLoad);
}
}
}
`

There is very little detail in your question. Please check the following:
1. Is the collider attached to both the player and the trigger object?
2. What are their settings? Kinematic,etc ?
3. do you have a RigidBody attached to the player or the trigger object?
4. Is the SceneToLoad already registered in the Build?
These are the basics to make what you want. I suggest you revise the following topics:
1. Collision, Colliders and Rigidbody, especially search for Collision matrix
2. How SceneManagement works

Is your game 3D or 2D? If its 3D, change the OnTriggerEnter2D to JUST OnTriggerEnter().
And check that the Is Trigger in the box collider (or whatever collider you're using) is checked. :)
You also put in a semicolon in the if(other...) so remove that. Semicolons aren't supposed to be put in to if statements

Related

How do I make a ProgressBar with rounded corners using Xamarin Forms

So my goal is to create a ProgressBar with rounded corners. This seems to be way harder than what it should be. I've tried looking at examples on StackOverflow but most of them are outdated or is referring to Android Studio which is NOT what I am working with.
As far as I know, I need to create a whats called "Custom Renderer" which is essentially a class that inherits from ProgressBarRenderer. And then change most of the properties there, which seems kinda silly since the UI should be done using XAML in my opinion.
I keep running into multiple issues when trying to create the custom renderer.
The first one being this
I've already installed Xamarin.Forms and it still keeps throwing that error.
And then there is a issue regarding the constructor. The constructor that doesn't take any parameters is obsolete and doesn't work anymore and it requires me to add a Context which I can't either because it throws the same error as above.
How do I properly create a progressbar with rounded corners and text in the middle indicating how much % it's at?
You should add proper reference to use the ProgressBarRenderer:
using App498.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
The custom renderer should look like this:
[assembly: ExportRenderer(typeof(Xamarin.Forms.ProgressBar), typeof(myProgressBarRenderer))]
namespace App498.Droid
{
public class myProgressBarRenderer : ProgressBarRenderer {
public myProgressBarRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.ProgressBar> e)
{
base.OnElementChanged(e);
}
}
}
If you want to add round corner to progress bar, check this thread.
I would refer you to SkiaSharp, graphics library, that enables you to create... well everything.
See the documentation here:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/
You'll need to play around for a while to get used to work with it, but it's quite intuitive and easy to work with.
To achieve round corners, you'll need to work with paths, described in here:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/curves/clipping
By a chance I also needed a progress bar in my app. I've drawn a picture with transparent line within for the progress to be shown, merged it with green rectangle (the progress itself) and voila, you've got the progress bar. When you need to update the progress, you just redraw the progress bar.
There are surely plenty of other solutions, but this one I reccomend as I know it will work fine.
Hapyy coding ;)

Unity UI not working properly ONLY on Windows

I have been working on figuring out what is going on with my game's UI for at least two days now, and no progress.
Note that this is a mobile game, but I was asked to build for Windows for visualization and presentation purpose.
So the problem is that when I run my game on the Unity Editor, Android, iOS and Mac platforms the UI works just perfect, but then when I run the game on Windows the UI still works fine UNTIL I load a specific scene.
This specific scene is a loading screen (between main menu and a level) when the level finished async loading, a method called MoveObjects is called in a script in the loading screen, to move some objects that where spawned in the loading screen scene into the level scene (this is not the issue though, since I already try without this method and the problem on the UI persist).
Once the logic of this MoveObjects method is done, a start button is enabled in the loading screen, for the player to click and start playing (I did try moving the start button to the level scene, since maybe it not been a child of the currently active scene could be the issue, but the problem still persist). Is at this point that the UI is partially broken, what I mean with this is, that I can see buttons (and some other UI elements like a scrollbar) changing color/state when the mouse moves over them, but I cannot click on them anymore (the button wont even change to the pressed state).
Also note that I tried creating a development build to see if there was any errors in the console, and I notice that this problem is also affecting the old UI system, so I was not able to interact with the development console anymore.
Also also, note that if I grab and drag the scrollbar before this issue appear, and I keep holding down on the scrollbar until this happens, the mouse gets stuck on the scrollbar, meaning that I cannot interact with the UI anymore, but the scrollbar will still move with the mouse.
I already check that this things are not the source of the problem:
Missing EventSystem, GraphicRaycaster or InputModule.
Another UI element blocking the rest of the UI.
Canvas is Screen Space - Overlay so there is no need for a camera reference.
I only have one EventSystem.
Time.timeScale is 1.
I am not sure what else I could try, so if anyone has any suggestions, I would appreciate it. Thanks.
P.S: I am sorry to say that I cannot share any code or visual material or examples due to the confidentiality.
A major source for a non-working UI for me has always been another (invisible) UI object blocking the raycast (a transparent Image, or a large Text object with raycast on).
Here's a snippet I put together based on info found elsewhere, I often use it to track objects that are masking the raycast in complex UI situations. Place the component on a text object, make sure it's at least few lines tall, as the results will be displayed one under another.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
public class DebugShowUnderCursor : MonoBehaviour
{
Text text;
EventSystem eventSystem;
List<RaycastResult> list;
void Start()
{
eventSystem = EventSystem.current;
text = GetComponent<Text>();
text.raycastTarget=false;
}
public List<RaycastResult> RaycastMouse(){
PointerEventData pointerData = new PointerEventData (EventSystem.current) { pointerId = -1, };
pointerData.position = Input.mousePosition;
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointerData, results);
return results;
}
void Update()
{
list= RaycastMouse();
string objects="";
foreach ( RaycastResult result in list)
objects+=result.gameObject.name+"\n";
text.text = objects;
}
}

How To Ignore Collision Between Two Objects On The Call Of A Script In Unity3D?

Basically, what I want to do is have two objects (fpscontroller and a wall) that collide like normal. But, once a script runs, they won't collide anymore.
So, how do I make that script that makes the two objects ignore collision with each other? I've tried looking this up, and what I got was Physics.IgnoreCollision, but the documentation on that confused me. And when I tried putting it in and replacing their variables with my variables, I got a bunch of errors.
So, please help.
The way i would go about doing this is through layers.
In unity, a convenient way to ignore physics collision between objects is through setting the object to be ignored to a layer which your player object will always ignore.
So, to go about setting this up imagine the following:
fpscontroller's layer is set to "player" (a layer i have created and named such).
wall's layer is initially always set to "wall" (once again a layer i have created)
Additionally, I create a layer that i call "IgnorePlayerCollisions"
Now i go to: Edit > Project Settings > Physics
Here i can check the box which will turn off collisions between my player and IgnorePlayerCollisions layers.
Now, at runtime i run my script which says:
Change Wall Layer to "IgnorePlayerCollisions". Voila, my player now ignores all collisions with this layer.
Code Examples: (You don't need these all):
// Function to Change a GameObject Layer to the Ignore Layer
public void ChangeGameObjectLayerToIgnore(GameObject go) {
go.layer = [Index of Ignore Layer];
}
// Function to Change "This" GameObjects layer to any other layer
public void ChangeThisGameObjectLayer(int layerIndex) {
this.gameObject.layer = layerIndex;
}
// Change a GameObject layer to another layer
public void ChangeGameObjectLayer(GameObject go, int layerIndex) {
go.layer = layerIndex;
}
How?
Place a C# function into a script and attach it to either your desired gameobject. In your case, i may attach it my Player GameObject since it seems like you may want to disable object throughout the game based on specific trigger or something. It really depends on how you plan to trigger the function.
Let me know if this makes sense or not. If not, i can attempt to make it more legible.
Good luck and have fun!

Turning an avatar into a 3rd person character

I just learned how easy it is to simply drag a 3rd person character controller prefab (from Unity's standard assets package) and drop it into the hierarchy.
Using the WSAD and Space keys feels pretty natural, so I wondered if I could apply the same character controller to a customized avatar.
Using the free AutoDesk Character Generator (https://charactergenerator.autodesk.com/) I created one (fbx file) and imported it into Unity, so now I have my own character prefab.
I, then, searched for the steps to animate it just like a a 3rd person character controller, with the following article coming up first, but I wonder if I always have to do all the steps?
http://blogs.unity3d.com/2014/04/14/turn-your-character-into-a-player/
Once you have a customized character in the form of a Unity prefab, should do still go through all these steps, or is there a simpler way of animating your avatar; e.g. adding the basic necessary scripts?
That article gives a good overview of what is required.
However, you can essentially skip almost all those steps when using autodesk character generator.
Here is a quick way:
Set your FBX to be a mecanim humanoid
Drag an mecanim animator controller onto it
Write your code to set the animator states (eg: speed, jumping, etc)
To do that:
Export from Autodesk as "Unity FBX" format to get YourCharacter_Unity.fbx
Drag the FBX into the unity project files
Click on the YourCharacter_Unity FBX in project (blue cube), select "RIG" tab in inspector, and change Animation type to "Humanoid" (which maps it to the Mecanim system).
Drag the FBX from the project into the scene.
Go to the Asset Store and import "Mecanim Locomotion Starter Kit" (which has a basic locomotion controller and a set of animations)
Drag the "Locomotion Setup/Locomotion/Locomotion.controller" onto the "controller" variable on your character's Animator component.
Untick "apply root motion"
Now, if you hit run you will see your character standing there with idle motions. If you double click on the animator controller on your character it will open up the Mecanim Animtor window and you can manually set the animation state. Try changing the speed to 1.0 and you will see him walk/run.
Note: In your character's Animator component if you checkmark "Apply root motion", then the feet animation will cause your avatar to automatically move when his speed > 0.
You say you are using a CharacterController, so here is a very simple script that references the character controller to get the current speed, and then set the speed on the Animator:
using UnityEngine;
using System.Collections;
public class CharacterAnimator : MonoBehaviour {
public CharacterController controller;
public Animator animator;
private int speedid;
void Start () {
animator = GetComponentInChildren<Animator>();
controller = GetComponent<CharacterController>();
speedid = Animator.StringToHash("Speed");
}
void Update () {
float speed = controller.velocity.magnitude;
animator.SetFloat(speedid, speed);
}
}

Unity GUI Text won't work

I have the following problem, and I'd appreciate greatly if someone could help.
I've been trying create a roll-a-ball game in Unity, similar as the one presented in one of the tutorials on their official website, but with one difference: I'd like to add GUI text that would show the score. Every time the ball hits (and destroys) one of the rotating cubes, the score should increase by 1, and the text should show the current score.
I've watched the following tutorial:
http://unity3d.com/learn/tutorials/projects/space-shooter/counting-points
I have created the UI text, called ScoreText, and, on the other hand, I have written the script that makes an instance of GUIText class, called guitext, show the current score. However, I cannot connect my particular GUI text (ScoreText) with the script, i.e. I cannot tell the script to use that particular GUI text to show score. In the video, at 16:35, they just drag the GUI text to the instance of the GUIText class from the script (in my case, guitext), in order to tell the script it's that particular text that should show the score. But when I try to drag it, I simply can't do it. I have no idea why.
I don't know if this could cause the problem: under "Create" in the free version of Unity, I could not find anything called "GUI text" but instead I created a UI text. I know it's the same thing, but... In the script, I define an instance of GUIText class - guitext - so maybe, when I try to add my UI text to it, it won't work because my text really doesn't belong to the GUIText class?
Since you are using Unity 4.6 which has a new GUI system and not the Legacy UI which was present when the tutorial which you mentioned was made. There are two options - either you create an empty gameobject and add add a GUIText component to it. You can add the GUIText to empty gameobject by selecting it in the Hierarchy which should display the objects properties in the Inspector panel.
In the Inspector, you should see an Add Component button, click on it and search for GUIText. Add it and that should solve your problem.
Oh yea, the second option is to migrate to Unity 4.6 new GUI, which should take time unless you are pretty good with unity.
If you want to learn Unity 4.6 GUI, you can refer these links
Unity Official
Unity 4.6 tutorials by TheGameContriver
I am only posting on this because many come to this one and get lost. Here is how to make this work in Unity5.3 at the time of this response.
This is in C#
Simply use the GameController game object to attach the script to. Second create a UI text. Toy only call it score or scoretext for your own referral otherwise the name itself does not matter.
using UnityEngine;
using UnityEngine.UI;///needed to reference the new UI setup in this script type
using System.Collections;/// <summary>
/// allows collections of related information.
/// </summary>
public class GameController : MonoBehaviour {
public GameObject targets;
public Vector3 spawnValues;
public int hazardCount;
public float spawnWait;
public float startWait;
public float waveWait;
public Text Text; /// <summary>
/// change this because you dont actually use the words UI or GUI. Thats just for the reference and not clarified by instructors.
/// </summary>
private int score;
void Start()
{
score = 0;
UpdateScore();
StartCoroutine(SpawnWaves());
}
IEnumerator SpawnWaves()///this depends on the above using System.Collections
{
yield return new WaitForSeconds(startWait);
while (true)
{
for (int i = 0; i < hazardCount; i++)
{
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(targets, spawnPosition, spawnRotation);
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds(waveWait);
}
}
public void AddScore(int newScoreValue)
{
score += newScoreValue;
UpdateScore();
}
void UpdateScore()
{
Text.text = "Score: " + score;
}
}
Confirmed. In the GameController.cs file, change the declaration of public GUIText scoreText to public Text scoreText, and then it will let you drag it on the Game Controller as the video shows.
Update your Unity tutorials, peoples! Just spent an hour trying to figure this out!
One more thing...check the Z position. My UI looked perfect head on in the scene view, but my text never showed in the game...then I rotated the scene view and found my text was way behind the camera. Seems when you add something to the UI, the z value is somewhat random.

Resources