- Home /
can't reference an instance of an object (prefab)
Hi all I've checked out other NullReferenceException questions, but I still don't understand why the following doesn't work:
public class Problem: Monobehaviour{
public GameObject spawnMarker;
public GameObject mySpawnMarker;
public void PreWaveEvent(){
determineSpawnPoint();
mySpawnMarker = Instantiate (spawnMarker, spawnPoint, Quaternion.identity) as GameObject;
Debug.Log (mySpawnMarker.transform.position);
}
}
spawnMarker references a prefab I drag an drop into it in the editor.
What happens is the following:
an instance of spawnMarker is succesfully created, I can see it in game mode.
However, all attempts to reference it using "mySpawnMarker" fail and throw a Null Reference Exception (Debug.Log was just for debug purposes, I originally tried Destroy(mySpawnMarker) and others). I don't understand why, because the same approach works for other objects in my game (though there I'm not instantiating from a prefab, but from another object that's in the scene). Thanks for your help!
Answer by D3ltaVyyb · May 09, 2014 at 11:14 AM
Hmm... I've had a few NRE's with prefabs Instantiating it like: "~~~) as GameObject;" Try this:
public class Problem: Monobehaviour{
public GameObject spawnMarker;
public GameObject mySpawnMarker;
public void PreWaveEvent(){
determineSpawnPoint();
mySpawnMarker = (GameObject) Instantiate(spawnMarker, spawnPoint, Quaternion.identity);
Debug.Log (mySpawnMarker.transform.position);
}
Or this is how I do it. Have a prefab in your resources folder called 'spawnMarker', and disregard assigning it in the editor and just call it from script.
public class Problem: Monobehaviour{
public GameObject mySpawnMarker;
public void PreWaveEvent(){
determineSpawnPoint();
mySpawnMarker = (GameObject) Instantiate(Resources.Load("spawnMarker"), spawnPoint, Quaternion.identity);
Debug.Log (mySpawnMarker.transform.position);
}
}
Also I see you're using spawnPoint. If that deter$$anonymous$$eSpawnPoint(); isn't setting spawnPoint , you might have to assign it like: spawnPoint = deter$$anonymous$$eSpawnPoint() or however you have it set up.
Thanks for your answer: The approach with the resources folder solved the problem.
For completeness' sake: I had tried the "(GameObject) Instantiate..." approach before but that gave me an "InvalidCastException: cannot cast from source type to destination type".
deter$$anonymous$$eSpawnPoint() was working ok, I left some stuff out in the code example so it wouldn't distract from the core issue.
Your answer
Follow this Question
Related Questions
Accessing a prefab after instantiating results as null 1 Answer
instantiated GameObject Prefab jumps in air after instantiate 1 Answer
NullReferenceException 2 Answers
How to manipulate a variable of a prefab script (instantiated) while the game is runnning . 1 Answer
Problem when setting variable in an instantiated gameobject 0 Answers