0

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!

Vivek Negi
  • 51
  • 1
  • 7

1 Answers1

1

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
}
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • 1
    Yeah, I just realized that when I manually changed the camera position to 2 and it instantiated the object fine. Rounding off the number works. Thank You. – Vivek Negi Jan 27 '18 at 12:37