Update instantiates more than 1 object

If the object has reach certain position.x, I want that that object clone itself, but in another position. I wrote this code in the Update function:

if(transform.localPosition.x <= -6.26f && canBuild == true)
		{
			canBuild = false;
			Instantiate(gameObject, new Vector3(transform.position.x + 15.65f, transform.position.y, transform.position.z), Quaternion.identity);
		}

I use localPosition because the object, in Start() is parent of the camera.

The code seems to run well, but sometimes, it enters twice in the IF sentence, so 2 objects are created instead of one.

Why is happening this? How can I fix it?

Depends on how many you want to spawn. If you want to control exact amounts, you could make either a list or a singular gameobject, as follows:

list<GameObject> horribleMonsters = new list<GameObject>();
//or
GameObject terribleBeast;


if(transform.localPosition.x <= -6.26f && canBuild == true)
{
canBuild = false;
if(terribleBeast == null)
{
terribleBeast = Instantiate(gameObject, new Vector3(transform.position.x + 15.65f, transform.position.y, transform.position.z), Quaternion.identity) as GameObject;
}
//or
if(!horribleMonsters.Exists(s => s.identifyingcharacteristicsuchasname("Steve"))
{
GameObject x = Instantiate(gameObject, new Vector3(transform.position.x + 15.65f, transform.position.y, transform.position.z), Quaternion.identity) as GameObject;
horribleMonsters.Add(x);
}
}

Keep in mind updateloop can fire multiple times a frame if your game hitches. Try setting timescale to 0 for instance, lots and lots of updateloops within singular frame.

Couldn’t find the reason, but instead of Instantiate/Destroy I made an Object Pool and solve this issue and also increased the performance!