GameObject instantiates too many objects in update

Hello, I wrote a code that should instantiate a prefab (edgePrefab) just when two other objects (node1 and node2) appear in the scene. However, as soon as both the objects appear in the scene, the prefab is instantiated continuosly in a loop.

I tried to use a bool to instantiate the object just once, but the problem in my code is that nodeSource and nodeTarget never become null.

I don’t want to destroy those objects, I just would like the prefab to appear in the scene only one time, as soon as the other two objects are both present in the scene.

Here is my code:

using UnityEngine;
using System.Collections;

public class DrawConnections : MonoBehaviour {
	
	public GameObject edgePrefab;

	bool firstUpdate = false;
	GameObject nodeSource = null;	
	GameObject nodeTarget = null;
	Vector3 pos = new Vector3(0, 0, 0);
	

	void Start () {
	}
	
	void Update () {
	
		if (firstUpdate != true) {	
		nodeSource = GameObject.Find("Node1");	
		nodeTarget = GameObject.Find("Node2");	
		}
		
		
		if (nodeSource != null && nodeTarget != null)
		{
		//	Debug.Log("Nodes exist");
			
		//Instantiate(edgePrefab, pos, Quaternion.identity);
		GameObject oneEdge = Instantiate(edgePrefab, pos, Quaternion.identity) as GameObject;
	
		nodeSource = null;
		nodeTarget = null;
		firstUpdate = true;	
		}
		
	}
}

Notice that if I put in the start function

Debug.Log("I start");

I see that the console prints “I start” many times… This shouldn’t happen and I think this is the real cause of my problem (that’s why the bool value doesn’t work). Why is the start funcion executed on each frame? Strange thing is if I comment line 30 (GameObject oneEdge = Instantiate…), then the start function is executed just once (i.e. “I start” printed just once in the console)

Thank you in advance for your help.

On line 32…

nodeSource = null;       
nodeSource = null;

Shouldn’t the second line be nodeTarget? And you’d need to set firstUpdate to true instead of false after that to prevent setting the node variables again.

You’re never setting firstUpdate to anything other than false, so it’s always running the code repeatedly.

Regardless, that’s kind of what the Start method is for - to execute things once only, at the start of the game, and let Update handle the rest. Rather than having all of this code in Update, just put the bits defining nodeSource and nodeTarget, followed by the Instantiate, in Start.

Start is slightly different from Awake in that Start guarantees that all objects are loaded into the scene before Unity calls it, while Awake doesn’t. This means that GameObject.Find will work perfectly well in Start.

Oh, and one more thing - you don’t need to assign the result of Instantiate to anything if you aren’t going to use it in the code later. Since you’re defining it as a temporary variable, the code just discards it immediately anyway, so there is literally no point in creating that variable.