- Home /
Instantiate() as GameObject = null reference
Hi, i'm getting a "null reference exception Object reference not set to an instance[...]"
I got this method inside the "SpawnObjects" class :
public class SpawnObjects : MonoBehaviour
{
public GameObject[] RandomGO;
public void spawnSomeObjects()
{
GameObject Gobj = Instantiate(RandomGO[0]) as GameObject;
Gobj.transform.position = new Vector3(0f, 50f, 5f);
}
}
After setting the lenght of the array and after placing the objects in it from the inspector, I try to call this method from the Update function of this other class :
public class BucketMovement : MonoBehaviour {
public float AssignTimeSpawn = 2.0f;
float TimeSpawn = 2.0f;
void Update ()
{
TimeSpawn -= Time.deltaTime;
if (TimeSpawn < 0)
{
TimeSpawn = AssignTimeSpawn;
SpawnObjects s = new SpawnObjects();
s.spawnSomeObjects();
}
}
And as I said, I get that null reference exceptions... Last question : if I set field members to public static, why they wont appear in the inspector?
Answer by robertbu · Apr 02, 2014 at 09:14 PM
You can't use 'new' with a class that is derived from MonoBehaviour. You need to get the component from the game object the script is attached to. Typically you would do it this way:
public class BucketMovement : MonoBehaviour {
public float AssignTimeSpawn = 2.0f;
float TimeSpawn = 2.0f;
SpawnObjects spawnObj;
void Start()
{
spawnObj = GameObject.Find("GameObjectWithSpawnObjectsScript").GetComponent<SpawnObjects>();
}
void Update ()
{
TimeSpawn -= Time.deltaTime;
if (TimeSpawn < 0)
{
TimeSpawn = AssignTimeSpawn;
spawnObj.spawnSomeObjects();
}
}
http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html