- Home /
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 :)
Answer by FunctionR · Nov 17, 2013 at 09:03 PM
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
Identify which GameObject has the Sheep script.
Get a pointer to that GameObject.
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.
It works when there is already game object in the scene. In my case, game object is not instantiated yet.
This is new code, but it doesn't work void Awake() { sheep = GameObject.Find("Sheep").GetComponent<Sheep>(); }
So, i need to access component of Sheep prefab which is not instantiated. btw, thx for response I really appreciate that :)
No problem. You can instantiate your prefab. Look at my Edit above, that should solve your problem.