Referencing a Public GameObject from another script.

I have two objects, TileSelect and GameMenu with scripts TileSelect and GameMenu attached respectively.

Different gameobject are fed into SetBuilding depending on which GUI button was pressed.

public class GameMenu : MonoBehaviour 
{
	public GameObject curBuilding;

//GUI Menu Script
{
  SetBuilding(buildings[x+y*invCol]);
}
	public void SetBuilding(GameObject b)
	{
		Debug.Log(b.name);
		curBuilding = b;
		Debug.Log(curBuilding);
	}
}

curBuilding updates in the inspector whenever I click a new GUI button. Whenever I try and reference curBuilding in Tile I always get Null. I have a feeling I’m missing a reference or a .transform but I can’t figure it out.

public class Tile : MonoBehaviour 
{
	public GameObject mapTile;
	public GameMenu gameMenu;

	public void OnMouseDown()
	{
		if(Input.GetMouseButtonDown(0))
		{
			Debug.Log("Right Mouse");
			Debug.Log(gameMenu.curBuilding);
			//Instantiate(gameMenu.curBuilding.transform, transform.position, Quaternion.identity);

Did you link gameMenu to the script in the inspector? Because that could lead to null variable. Click on your object containing the tile script and drag your object containing the GameMenu class in the slot for "Game Menu" field.

2 Answers

2

In the GameMenu code above, you’re never calling SetBuilding(buildings[x+yinvCol]);* so it’s not surprising that curBuilding is always null - it never gets assigned a value.

Try initialising curBuilding to a non-null value (e.g. in Start() of GameMenu) and check that you can retrieve that value from Tile.

p.s. you’ll find it easier to see where your code is failing if you make your Debug.Logs more descriptive. e.g.

 public void SetBuilding(GameObject b)
{
...
Debug.Log("Value of curBuilding in SetBuilding() is: " + curBuilding);
...
}

Otherwise you’re just printing the name of the building lots of times but can’t tell why.

Thank you very much for the response. I'm new to Unity. I'm going to try this later when I get out of work.

And what is the value of x+y*invCol? Is it less than the length of the buildings[] array?

Solved it. Trying to modify the variable from the GameMenu only changes the prefab GameObject and not the instansiated clones. Referencing the GameMenu from the cloned GameObjects TileSelect Script works.

public void OnMouseDown()
{
	if(Input.GetMouseButtonDown(0))
	{
		GameObject gm = GameObject.FindWithTag("GameMenu");
		tileBuilding = gm.GetComponent<GameMenu>().curBuilding;
		Instantiate(tileBuilding, transform.position, Quaternion.identity);

Thank you everyone for your responses.