- Home /
NullReferenceException: Object reference not set to an instance of an object
I currently have 2 GameObjects inactive and not showing in the game camera window, I want to active these GameObjects when there has been a collision with an object already in the game. I have this code but it doesn't seem to be working.
using UnityEngine;
using System.Collections;
public class GunPickUP : MonoBehaviour
{
public GameObject Weapon1;
void Start()
{
Weapon1 = GameObject.Find ("Weapon1");
}
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "HellGuns")
{
Weapon1.SetActive(true);
other.gameObject.SetActive(false);
}
}
}
Those GameObjects should be active on the hierarchy for GameObject.Find to actually find them
Answer by perchik · Feb 27, 2014 at 02:08 PM
Check this thread for ideas on how to solve NRE.
http://answers.unity3d.com/questions/528288/null-reference-exception-what-is-it-and-why-do-i-g.html
My initial guess is that GameObject.Find ("Weapon1");
doesn't actually find anything.
It should do though as I have the GameObject named 'Weapon1'. If I change it to findwithtag and select the correct tag still comes back with same error.
No, perchik is probably right. Since you start with the gameObjects turned off, the find statement can't find them. To fix this, you can start with the gameObject on and then immediately after the find statement turn off Weapon1 in that script.