Reputation: 33
I'm creating a game in Unity and for my level select, I'm using a world that you walk around in and approach a node that would take you to the level you want to go to. Kind of like a Mario level select. I have a player and a node in the world. The node has two box colliders, one to detect the player nearby, and the other that just surrounds the box outline. The bigger collider has the IsTrigger checked, the other does not. I'm trying to get the node to detect whether the player is in the outside area or not, but code isn't working and I'm not sure why.
Here is the code for the player:
public class Player : MonoBehaviour {
public GameManager manager;
private Vector3 spawn;
public bool usesManager = true;
private bool levelComplete;
public AudioClip[] audioClip;
void Start()
{
if (usesManager)
{
manager = manager.GetComponent<GameManager> ();
}
levelComplete = false;
spawn = transform.position;
}
void Update()
{
Movement();
}
void Movement()
{
if (!levelComplete)
{
if (Input.GetKey (KeyCode.A))
{
transform.Rotate(0, Input.GetAxis("Horizontal") * 2.0f, 0);
}
if (Input.GetKey (KeyCode.D))
{
transform.Rotate(0, Input.GetAxis("Horizontal") * 2.0f, 0);
}
if (Input.GetKey (KeyCode.S))
{
transform.Translate (Vector3.forward * 3f * Time.deltaTime);
}
if (Input.GetKey (KeyCode.W))
{
transform.Translate (Vector3.back * 3f * Time.deltaTime);
}
}
}
void OnCollisionEnter(Collision other)
{
if (other.transform.tag == "Enemy")
transform.position = spawn;
}
void OnTriggerEnter(Collider other)
{
//finds friend
GameObject friend = GameObject.FindGameObjectWithTag("Friend");
if (other.transform.tag == "Sensor" && (Mathf.Abs ( friend.transform.position.x - transform.position.x) <= 4))
{
levelComplete = true;
PlaySound (1);
manager.CompleteLevel();
}
if (other.transform.tag == "Token")
{
if (usesManager)
{
manager.tokenCount += 1;
}
PlaySound (0);
Destroy(other.gameObject);
}
}
void PlaySound(int clip)
{
audio.clip = audioClip [clip];
audio.Play ();
}
}
Here is the code for the node:
public class LevelLoader : MonoBehaviour
{
public int levelToLoad;
void OnTiggerStay(Collider other)
{
if (other.transform.tag == "Player")
Debug.Log ("hit");
}
}
When the player enters the trigger, nothing shows up in the console. Any help would be much appreciated!
Upvotes: 0
Views: 9122
Reputation: 1
You Used OnTiggerStay not OnTriggerStay thatswhy this not work.
Upvotes: 0
Reputation: 395
In you coder, you have written OnTiggerStay
instead of OnTriggerStay
.
It is also important that one of the colliding objects has a rigidbody
attached, or the OnTriggerStay
event will not be invoked.
Note that trigger events are only sent if one of the colliders also has a rigid body attached.
You can read more about this here.
I would also recommend not using on trigger stay altogether, and keeping track of Enter/Exit yourself. This will give you slightly more control, and stops Unity from handling something that you should really be handling.
Upvotes: 3