I have a C# script where I am instantiating a prefab inside of a coroutine. When I attempt to access that prefab from another coroutine or anywhere else in the code, I am getting a null reference exception; however, I know that the object exists, as I can see it on-screen, and I can reference it later in the same coroutine that instantiates it. Here is the relevant code:
private Vector3 originalPosition = new Vector3 (0, 0, 0);
public GameObject masterPrefab;
private GameObject instantiatedPrefab;
void Start ()
{
instantiatedPrefab = null;
}
private IEnumerator SpawnPrefab ()
{
if (instantiatedPrefab == null)
{
instantiatedPrefab = (GameObject)Instantiate (masterPrefab, originalPosition, new Quaternion (0, 0, 0, 0)) as GameObject;
}
print ("Prefab created at " + instantiatedPrefab.transform.position.ToString ());
}
If I call StartCoroutine (SpawnPrefab ()),
the prefab is instantiated. I can see it on the screen and it behaves as expected. The print statement accesses the instantiated prefab’s position and prints it correctly. However, if I attempt to acces the instantiated prefab anywhere else – in Update
, or another coroutine, for example – I get the null reference exception. So the following will throw that error:
private IEnumerator DoSomethingWithPrefab ()
{
print ("Do something with prefab located at " + instantiatedPrefab.transform.position.ToString ());
}
As well as this:
void Update ()
{
print ("Prefab position: " + instantiatedPrefab.transform.position.ToString ());
}
I’m stumped. I figured if I successfully instantiated the object, I would be able to manipulate it within the script, but I’m clearly missing something.