- Home /
C# nullreferenceexception object reference not set
In my game the player starts in a town, I want the monster to spawn when you leave the town. So I have created a cube with no renderer and made it a Box Cillder that IS a trigger. I have written this code and applied it to the cube.
using UnityEngine;
using System.Collections;
public class NightStalker_active : MonoBehaviour
{
public Vector3 spawnPosition = new Vector3(-2406, -18, 51);
void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Player")
{
Debug.Log("NightStalker_active_TOUCH: ");
//GameObject.FindGameObjectWithTag("NightStalker").SetActive(true);
GameObject.FindGameObjectWithTag("NightStalker").transform.position = spawnPosition;
}
}
}
I have tried to set the monster (NightStalker) to active and just letting it say active but move it to a new position (Hiding it somewhere in a box). I cant see to get this to work. I can get objects set active false with trigger volumes, I use one to turn off the rain when you walk into a building but cannot switch it back on.
Please, How can I get my object or something tagged to be setactived or its tranform moved?
Answer by perchik · Apr 16, 2014 at 07:24 PM
Your error says that GameObject.FindGameObjectWithTag("NightStalker")
is not returning anything, but you're trying to use it. Make sure that you have an object that is tagged "NightStalker".
GameObject nightStalker = GameObject.FindGameObjectWithTag("NightStalker");
if(nightStalker==null){
Debug.Log("no night stalker found");
}
I used this code and added a else statment if it found the object, and I got back the found log. So it is able to find the tagged object.