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.