- Home /
Distance check between player and empty object with box collider not working
I want to move the player to a new scene when he gets close to an EmptyObject that has a box collider. This is the current code:
void Update () {
var dist = Vector3.Distance(GameObject.FindGameObjectWithTag("Player").transform.position, gameObject.transform.position);
if (dist< 2)
{
SceneManager.LoadScene(nazivScene);
Debug.Log("Igrač pokušava ući u novu scenu (taverna)");
}
}
Sadly, it's not working. If I put if(Input.GetKeyDown(KeyCode.F)
then it works so there is no problem with the scene but I want the player to move to new scene when he gets close to the box collider. What's wrong?
When you use a box collider, why do you use the distance-check. I guess, what you want is a trigger https://unity3d.com/de/learn/tutorials/topics/physics/colliders-triggers There you have an extra function, called OnTriggerEnter https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html that is called when something goes inside the trigger.
Answer by zarkosrbija · Sep 08, 2017 at 11:38 AM
The easiest way to do that is to add in player script public GameObject myGameObj;
then link that game object to player script in unity editor, and then make in player script another variable private Vector3 distance;
and then in Update:
Update() {
distance = myGameObj.transform.position - gameObject.transform.position; //gameObject.transform.position is a Player position
if(distance.magnitude < = 2 ){
//do something, in your case load scene
}
}
Pozdrav!! :D