I have two scripts in my game which cycle through objects and do stuff with them (if they exist). The problem is that I’ve noticed some very strange and frustratingly inconsistent behaviour with array references.
Take the following, which finds the player’s base and returns them to it. Sometimes it works, sometimes it doesn’t. To my knowledge nothing important changes to cause it to success or fail, it just does that on a whim.
// find home button
if (Input.GetKeyDown(KeyCode.H))
{
GameObject[] home;
home = GameObject.FindGameObjectsWithTag("building");
GameObject goTo = gameObject;
for (int i = 0; i < home.Length; i++)
{
if (home*.GetComponent<Building>().unitMaster == gameObject)*
-
{*
_ goTo = home*;_
_ }_
_ }*_
* if (goTo != gameObject)*
* {*
* GameObject camera = Camera.main.gameObject;*
* camera.transform.position = new Vector3(goTo.transform.position.x-14, goTo.transform.position.y+28, goTo.transform.position.z-14);*
* }*
* }*
The other example suffers the same problem, the error is sometimes thrown that no instance exists when clearly the objects that it is searching for do exist with the right tag etc. What I found even more baffling is that without the Debug.Log prior which refers to the array length it will fail. Otherwise, with the Debug left in, it works. I don’t understand that in the slightest.
* void Grow2()*
* {*
* GameObject[] mushrooms = GameObject.FindGameObjectsWithTag(“mushroom”);*
* for (int i = 0; i < mushrooms.Length; i++)*
* {*
_ // For some bizarre reason it will throw an error about mushrooms not being an instance without this!
* Debug.Log ("mushrooms.Length "+mushrooms.Length);
if (mushrooms.GetComponent().height == 2)
{
// mushroom must be able to grow*
if (mushrooms.GetComponent().transform.localScale.x < mushrooms*.GetComponent().stopSize)
{
// check for collision with non-tile objects (this will stop growth!)
Collider [] colliders = Physics.OverlapSphere(mushrooms.transform.position, mushrooms.GetComponent().growFloat * 0.8f);
for(int j = 0; j < colliders.Length; j++)
{
if (colliders[j].tag != “tile” && colliders[j].tag != “unit” && colliders[j].gameObject != mushrooms)
{
mushrooms.GetComponent().stopSize = mushrooms.GetComponent().growFloat;
}
}
// grow mushroom*
if (mushrooms.GetComponent().transform.localScale.x < mushrooms*.GetComponent().stopSize)
{
mushrooms.GetComponent().growScale.x += 0.1f;
mushrooms.GetComponent().growScale.y += 0.1f;
mushrooms.GetComponent().growScale.z += 0.1f;
mushrooms.GetComponent().growFloat += 0.1f;
mushrooms.GetComponent().transform.localScale = mushrooms.GetComponent().growScale;
}
}
}
}
}*
I’m at a loss, I don’t understand what the problem is since the error seems to happen quite randomly sometimes, and then other times it works without flaw. What could be the cause of the problem?_