Vivek Negi
Vivek Negi

Reputation: 51

Object not instantiating, when comparing position in Update()

I have this script attached to the Main Camera. I want to instantiate an object whenever the camera is at a specific position in the y axis. But the object doesn't instantiate. Here's the script.

public GameObject obj;

private void Update()
{
    if (transform.position.y % 2 == 0) {

    Instantiate(obj, new Vector3(transform.position.x, transform.position.y), Quaternion.identity);

   }

}

Is it something to do with the modulus function? Thank you!

Upvotes: 0

Views: 29

Answers (1)

Programmer
Programmer

Reputation: 125455

It's not instantiating because if (transform.position.y % 2 == 0) { is not true. The reason if (transform.position.y % 2 == 0) is not evaluating to true is because transform.position.y is a float. When you divide that float by 2, the remainder will likely not be a 0.

Round that float to the nearest int before you comparing it to 0.This can be done with Convert.ToInt32 or Math.Round. There are other ways to do this too.

if (Convert.ToInt32(transform.position.y) % 2 == 0)
{
    //Instantiate
}

Upvotes: 1

Related Questions