Why do I keep getting 'The object you want to instantiate is null' warning?
I'm a beginner in C# and I'm currently working on script for my 2D game, where I would like random objects to fall from the top of the screen, from random locations, however for some reason, when I run my game in Unity, I keep getting a warning that says:
'Arguement Exception: The Object you want to Instantiate is null. UnityEngine.Object.CheckNullArgument.'
Anyone know how to fix this ?
public class FallingObjectBehaviour : MonoBehaviour {
public float spawnTime =3f;
public GameObject[] FallingObjects;
public Transform[] spawnPoints;
public int FallingObjectsSpawn;
public float fallSpeed = 10f;
void Start () {
FallingObjects = new GameObject[5];
FallingObjects [0] = GameObject.FindGameObjectWithTag ("Cherry");GetComponent<SpriteRenderer> ();
FallingObjects [1] = GameObject.FindGameObjectWithTag ("Strawberry");GetComponent<SpriteRenderer> ();
FallingObjects [2] = GameObject.FindGameObjectWithTag ("Apple");GetComponent<SpriteRenderer> ();
FallingObjects [3] = GameObject.FindGameObjectWithTag ("Grape");GetComponent<SpriteRenderer> ();
FallingObjects [4] = GameObject.FindGameObjectWithTag ("Bomb");GetComponent<SpriteRenderer> ();
}
void Update () {
FallingObjectsSpawn = Random.Range (0, 4);
Spawn ();
}
// Use this for initialization
void Spawn () {
int spawnPointsIndex = Random.Range (0, spawnPoints.Length);
Instantiate (FallingObjects[Random.Range (0,4)], spawnPoints[spawnPointsIndex].position, spawnPoints[spawnPointsIndex].rotation);
transform.Translate (Vector3.down * fallSpeed * Time.deltaTime);
if (transform.position.y < 4)
InvokeRepeating ("Spawn", spawnTime, spawnTime);
}
}
Answer by Morgenstern_1 · Oct 14, 2016 at 08:58 AM
One (or more) of the "FindGameObjectWithTag" calls is not finding an object. So there are null objects in your FallingObjects array, which means when you run the Instantiate line it is failing.
Do you have objects in your scene with those tags?
Also the "GetComponent();" call is doing literally nothing, get rid of those!
Also, why not just drag and drop your "FallingObjects" into the array in the inspector, rather than searching for them at startup? Depending on the size of your scene this can be really expensive!