Stop Object from instantiating multiple times in Update using bool

This is the script. I want the object to instantiate only once every time the y position is a multiple of 4. But the object gets instantiated multiple times as long as the y position is stuck at 4. I want to it to instantiate only once. Here’s the script.

public GameObject obj;
bool check = true;


private void Update()
{

    if (Mathf.Round(transform.position.y) % 4 == 0 && check)
    {
        check = false;
        Spawn();

    }
}

public void Spawn()
{

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

}

Thank You!

you can simply achieve that by buffer your game object’s last position and compare it with its current position. If they are the same, which means the game object is still, then do not trigger the function.


if(.............&&.........&&lastposition!=transform.position){
 //your code herer
}

lastposition = transform.position;