- Home /
Distance between two objects Unity
I want to find the distance between the player and the projectile.
this is what I tried:
public GameObject other;
void Update(){
float dist = Vector2.Distance(other.transform.position, transform.position);
print("Distance" + " " + dist);}
the ProjectileController:
MyRB = GetComponent<Rigidbody2D>();
MyRB.AddForce(transform.right * rocketSpeed, ForceMode2D.Impulse)
gunController:
Instantiate(bullet, guntip.position, guntip.rotation);
I changed the question a bit (to clarify it). The code didn't work for for some reason. The value always remains the same. Even when projectile comes closer.
maybe my question is stupid but maybe is this the problem.
have the variable other
the GameObject you want to compare distance?
because this public GameObject other;
is the way to store prefabs on script, and on your example code not have any instantiate, so you maybe are picking up the prefab but the current instance to made the comparision.
so again, in other words, What have you on the variable other
? you are trying to know the distance between the GameObjet to have asociate the script and other
, because the way you declare other
I think to you Drag & Drop a prefab inside it, if this is the problem, is the cause to the distance never change, you need to asign other
with the instace of this prefab, in other words with the projectile to see approach on the game.