Unity3d Script does not work anymore
I was working on a simple tank game. When the script I was using before suddenly stop working. I keep receiving the NullReferenceException: Object reference not set to an instance of an object error. I searched many questions online but none of them are similar to mine. The game object component that the unity engine claims is null is the parent of the script with the error. Moreover the script being referenced is what controls my game object which it does fine. Everything worked fine until I restarted my computer. I have gone over my script over and over and nothing have been changed but I keep getting the error. Here is the script with the error:
private GameObject i;
// Use this for initialization
void Awake () {
i = GameObject.FindGameObjectWithTag("WallBoy");
}
void Start () {
i = GameObject.FindGameObjectWithTag("WallBoy");
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ("Walls")) {
i.GetComponent<TW>().x += 1;
}
}
}
When I tried out your script, there was an error with the line:
i.GetComponent<TW>().x += 1;
The namespace 'TW' couldn't be found. So what exacly is TW?
Also, I don't think you need to find your gameobject in both Start and Awake.
TW is a script attached to the parent GameObject that controls the main player, which it does fine. The main player has the tag "WallBoy". The script worked fine when I first made it. However after I shut down my computer and restarted it, I began to get the null reference error. I have also checked the scripts and gameObjects many times and nothing seems to have changed.
Very strange... I'm not sure what's going on. Sometimes, the 'NullReferenceException' is caused by something not being assigned in the inspector. Is the error always there or does it appear when you hits the wall?
Replace your code with this, and let me know what it says.
private GameObject i;
void Start()
{
GameObject[] allWallBoys = GameObject.FindGameObjectsWithTag("WallBoy");
if (allWallBoys.Length > 1) Debug.Log("There are multiple instances of Wall Boy in this scene");
if (GameObject.FindWithTag("WallBoy") != null) i = GameObject.FindWithTag("WallBoy");
else Debug.Log("Unable to find Wall Boy");
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Walls"))
{
if (i.GetComponent != null) i.GetComponent<TW>().x += 1;
else Debug.Log("No TW component attached to i");
}
}
Answer by meapps · Oct 19, 2016 at 09:17 AM
Broken Tags, just use an other tag that will solve it. Somehow updates seems to break stuff.
Your answer
Follow this Question
Related Questions
Gameobject reference disappears at start 1 Answer
NullReferenceException Error 0 Answers
Problem Destroying Component 0 Answers
why i am getting this errorr.... 1 Answer