- Home /
Instantiate gameObject returns null?
Hi forum, I am new to unity and this is my first project.
I am trying to instantiate a gameObject and do something with it later.
public class spawnBase : MonoBehaviour {
public Transform baseSpawn;
public Transform baseSpawn;
// Update is called once per frame
void Start () {
GameObject temp= Instantiate(baseSpawn,new Vector2(spawnObject.position.x,0.73f),spawnObject.rotation)as GameObject;
int index = globalScript.getFreeQueue();
globalScript.setArray(index,temp);
if(temp==null){
Debug.Log("not supposed to be null");
}
temp.GetComponent<localVariables>().index = index; //returns error
}
error: NullReferenceException: Object reference not set to an instance of an object. So I found out that temp is indeed null. But the clone object shows up in both the camera and the hierarchy window. objectname(clone). So its both null and not null?
I have also try to instantiate with Quaternion.identity as the last parameter, but it gives the same error message.
Both of these are runtime errors.
What am I doing wrong here? Thanks for your time!
Are you sure it's not the Getcomponet call that is returning null? Can you post the full error message.
Answer by NoseKills · May 31, 2014 at 01:20 PM
The object you are trying to instantiate is a Transform. You are trying to instantiate a Transform as GameObject which is not possible.
If baseSpawn
is a Transform, you must instantiate (cast) it as a Transform. If you make the baseSpawn
field to be of type GameObject, the code will work (you need to drag and drop the prefab in the editor again to re-establish the connection after changing the type)
public GameObject baseSpawn;
// Update is called once per frame
void Start () {
GameObject temp = Instantiate(baseSpawn) as GameObject;
will work, as will
public Transform baseSpawn;
// Update is called once per frame
void Start () {
Transform temp = Instantiate(baseSpawn) as Transform;