NullReference

Hello everyone,
I’m new to unity 4.3 and I have a problem.
So, I’ve created a prefab which contains a script Spawner.

public GameObject sheepToSpawn;
public GameObject powerUpToSpawn;

Sheep sheep;
//PowerUps powerUps;

void Awake()
{
    sheep = GetComponent<Sheep>();
    //powerUps = GetComponent<PowerUps>();
}

void Update()
{
    sheep.SpawnSheep(sheepToSpawn);
    //powerUps.SpawnPowerUp(powerUpToSpawn);

}

In the inspector, I put another prefab, which contains script Sheep, into sheepToSpawn field of the first prefab.
Sheep class:

public void SpawnSheep(GameObject sheepToSpawn)
{
    for (int i = 0; i <= Random.Range(1, 5); i++)
    {

        listOfSheeps.Add((GameObject)Instantiate(sheepToSpawn, new Vector3(Random.Range(-7.0f, 7.0f), Random.Range(-4.0f, 4.0f), 0), transform.rotation));

    }  
}

I’m also getting this error :
NullReferenceException: Object reference not set to an instance of an object
Spawner.Update () (at Assets/Scripts/Spawner.cs:26)

If someone can help me with this problem and edit code if possible, I would be grateful.
Thanks in advance :slight_smile:

Your problem is here:

void Awake()
{
    sheep = GetComponent<Sheep>();
}

sheep is actually being set to null, because GetComponent() is not finding your Sheep script. It can’t find it because you are looking for the script inside the Spawner GameObject.

Solution

  1. Identify which GameObject has the Sheep script.
  2. Get a pointer to that GameObject.
  3. Use the pointer to find the Sheep script inside that GameObject.

Edit because of the code you posted below:

public GameObject sheepToSpawn;

Since sheepToSpawn points to the prefab, you have most of your problem solved already!

In the Awake() function you can instantiate the prefab. Like this:

void Awake()
{
   GameObject sheepObj = Instantiate(sheepToSpawn) as GameObject;

   sheep = sheepObj.GetComponent<Sheep>();
}

Now sheep points to the script in the instantiated GameObject.