It seems as if since upgrading to unity 5.0.2, this method will randomly fail. My project could be working fine the day before, but then it just poops out the next day, with the only difference being that my computer was turned off. And the weirdest part, is that I can that method several times in several classes. And they all work, except when trying to find one specific object. And yes, I did check if my tags somehow got messed up, and they’re all fine. Has anyone encountered something similar? Or know what could be causing this? Is there maybe some setting or an override method, which will ensure that the object which fails is loaded before any other?
Thank you
You basically have 2 options here:
-
You can use GameObject.FindWithTag() which will return 1 result based off the GameObject that has the tag.
public GameObject myGameObject;
void Start ()
{
//Single result. 1 GameObject.
myGameObject = GameObject.FindWithTag(“”);
//Do something with the GameObject.
Instantiate (myGameObject, whateverVector, whateverRotation);
}
-
GameObject.FindGameObjectsWithTag() constructs an array of GameObjects that share the same tag (which I believe you are using). To call a GameObject with this 2nd method you would need to call for it by index.
//This requires array brackets.
public GameObject myGameObject;
void Start ()
{
//Wrong way to call it. Remember, it’s an array.
myGameObject = GameObject.FindGameObjectsWithTag(“”);
//Adding brackets allows index to fill appropriately.
myGameObject = GameObject.FindGameObjectsWithTag(“”);
//You can also explicitly declare a single index.
myGameObject[0] = GameObject.FindWithTag(“”);
}
Not that the 2nd one isn’t actually incorrect, but the result depends on how it fits into the code.
If you do choose to use the second method to do the job, remember it needs the index and brackets.
Instantiate (myGameObject[0], whateverVector, whateverRotation);