Hi, I’ve been struggling with this problem for a while now;
So I have this prefab, which has children called squares:
And each of those children have a script, which has a GameObject variable called onThisSquare. By default it is null, and I’ve checked each child to make sure it is so.
Then I have a piece of code which instantiates the prefab at Vector3.zero at Start(), and nothing else. When I open my project for the first time and hit play, the prefab appears normally. But problems start appearing because of one game object, which has this piece of code:
if(Input.GetKeyDown(KeyCode.Space))
{
Transform startTile = currentTiles[0].tile.transform; //currentTiles is a list that stores the prefab
GameObject startSquare = startTile.GetChild(Random.Range(0, startTile.childCount)).gameObject;
Square startInfo = startSquare.GetComponent<Square>();
transform.position = startSquare.transform.position;
currentSquare = startSquare;
startInfo.onThisSquare = gameObject;
Debug.Log("On this square: " + startInfo.onThisSquare);
Debug.Log("Current square: " + currentSquare);
}
(So it should move my game object called Cube on a random square and set that square’s onThisSquare variable equal that gameObject)
The object moves to the correct location when I press space, but the variable doesn’t work properly. When I Debug.Log the onThisSquare variable, it is equal to my cube game object as it should…
…but on the inspector it shows null:
So that’s my first problem. But it gets weird.
When I stop my game, and then start it again, the inspector then shows the variable. Which is weird since on Start() no variables are assigned and I haven’t pressed space yet.
Now, if I move my cube again with space, the same problem appears.
This time currentSquare is Square12.
In the console it’s onThisSquare equals Cube.
In the inspector it’s onThisSquare equals null.
I restart the game.
And now BOTH Square7 and Square12 have Cube as their onThisSquare variable. Right from the Start().
And the problem repeats when I hit space, restart and so on.
I have checked that there aren’t any other scripts messing with these variables, and for the sake of testing, I’ve pretty much disabled all other scripts and methods.
So if anyone can help out a beginner with the variable problem and explain why prefabs work the way they do, it would be much appreciated.