NullReferenceException: Object reference not set to an instance of an objectInt32)

My basic aim in this project when I hit on cube my console should say : Cube Hit

using UnityEngine;
using System.Collections;

public class rotation : MonoBehaviour {
	public float speed =3f;
	public GameObject exPrefab;
	SpawnObjects so;
	// Use this for initialization
	void Start () {
		so = GetComponent<SpawnObjects> ();
	}
	
	// Update is called once per frame
	void Update () {
		transform.position -= new Vector3 (0.0f, speed, 0.0f) *Time.deltaTime;
		transform.Rotate (new Vector3 (15,30, 45) * Time.deltaTime);	

	}


	void OnMouseDown()
	{
		Destroy (this.gameObject);
		Instantiate (exPrefab, transform.position, Quaternion.identity);
		Check4Cube();


	}

	void Check4Cube()
	{
		foreach (GameObject go in so.prefabs) {
			if (go.tag == "Cube") {
				Debug.Log ("Cube hit");
			} else {
				Debug.Log ("NO");
			}
		}
	}



}

Error :
NullReferenceException: Object reference not set to an instance of an object
rotation.Check4Cube () (at Assets/Assets/Scripts/rotation.cs:32)
rotation.OnMouseDown () (at Assets/Assets/Scripts/rotation.cs:25)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)

1 Answer

1

As you’re aware, Check4Cubes has a for-each loop iterating through prefabs in “so.prefabs”.

So I have to ask, does the cube have a SpawnObjects component attached? And does the prefabs array contain objects? Because that seems to be what the error is referring to.

Although, it seems funny that each spawned object will contain another SpawnObjects script. Intended? Usually the way is to have one ObjectPoolManager or SpawnManager (SpawnObjects) and the objects are independent. Not each object containing another spawn manager. The simplest solution is to remove the Check4Cube function, you can assume the object being hit is the one calling OnMouseDown.

 void OnMouseDown()
 {
     Destroy (this.gameObject);
     Instantiate (exPrefab, transform.position, Quaternion.identity);

     //Check4Cube();
     Debug.Log("Cube hit"); 
 }