I am learning Unity with c#. I wrote some lines of code, so that an object moves forward while its z coordinate is less than 4, and when the z coordinate is actually 4, it prints a message to the console. Here it is:
void Update()
{
if (transform.position.z==4)
{
Debug.Log("we are here");
}
if (transform.position.z<4)
{
transform.position=transform.position (transform.forward*Time.deltaTime);
}
}
When I run the code, the object moves until its z coordinate gets to 4, as expected. the problem is that, when it gets to 4, the console does not print the "we are here" message. Why it is not happening?
CodePudding user response:
Try:
Console.WriteLine("we are here");
CodePudding user response:
because transform.position.z is float type and as you written in the update method the value of z is gonna change to --> the current value (time.delta time)
which mean the value is going to add some fractions to it every frame so it's almost gonna be have some fractions and it's gonna be hard to get excatly 4 as a value
instead try using
if (transform.position.z >= 4) { Debug.Log("we are here"); }