- Home /
The question is answered in the comments
Find with tag throwing an Null exception
Hey guys, I come up with a problem and I tried to resolve it by a numerous ways with no luck that I'm starting to get a bit crazy lol, because I think its a stupid problem.
So my problem is that I'm trying to get a GameObject through FindWithTag, but unity just keekps throwing a Null reference exception! I dont know why, I have the prefab tagged in the editor and have no mispelling errors, and I tried diferent names of tag with no luck aswell.
Here's me code (part of it):
public class Item: MonoBehaviour {
public GameObject Player;
public bool CanDo = false;
void Awake () {
if (Player == null) {
Player = GameObject.FindWithTag ("PlayerOwner");
}
}
void Update () {
if (Vector3.Distance (Player.transform.position, transform.position) < 5) {
CanDo = true;
}
Hope you guys can help me! Thanks in advance!
In order to find an object (GameObject.Find() or GameObject.FindWithTag()), the object must exist in the scene (i.e. cannot just be a prefab), and it must be active. Any change the 'PlayerOwner' object is not created at this point in the game? Does moving this code to Start() fix the problem?
No, Start doesnt solve the problem, and yes the playes is instantiated when the game plays, thats may be the problem, so is there any way arround? Thx
If ti$$anonymous$$g is your problem, you can work with script execution order and the use of Awake() vs. Start() to solve the problem. You could also delay just a bit initializing 'Player', but if you do, you'd have to also check for null in Update():
IEnumerator Start() {
yield return new WaitForSeconds(0.2);
if (Player == null) {
Player = GameObject.FindWithTag ("PlayerOwner");
}
}
And in Update():
if (Player == null) return;
Answer by Forte259 · May 08, 2014 at 08:25 PM
I've fixed it, the problem was indeed the order of instatiating the objects, so I changed it up a little and it works fine rigth now. Thank you for the help!
Follow this Question
Related Questions
Best method to manage multiple tags 2 Answers
Find a shader not in the scene 1 Answer
Can't find gameobjects being spawned getting a nullreferenceexception 1 Answer
How to use if statement properly 1 Answer
NullReferenceException 2 Answers