2 Identical scripts, the second can't access the variables of another object

Hi,

I am having a problem accessing the variables in my Game Controller from another object. My GameController holds the names from playerPrefs, and I am trying to access them from other objects, and use 3d texts. The strange part to me is that I can access it fine from some classes, but not from others. I have created several different classes, and copied and pasted the code from the classes that work, but sometimes the new classes will have access to the variables, and sometimes they won’t.

Below is the code from my Game Controller:

public class GameController : MonoBehaviour {

	public string name1;
	public string name2;
	public string name3;
	public string name4;
	
	void Start () {

		name1 = PlayerPrefs.GetString ("name1");
		name2 = PlayerPrefs.GetString ("name2");
		name3 = PlayerPrefs.GetString ("name3");
		name4 = PlayerPrefs.GetString ("name4");
	}
}

Below is the code for the working class that can take name1 from the Game Controller:

public class Name1Controller : MonoBehaviour {

GameController gameController;
private string name1;

void Start () {

	GameObject varGameObject = GameObject.Find ("Game Manager");
	gameController = varGameObject.GetComponent<GameController>();
	name1 = gameController.name1;

	GetComponent<TextMesh>().text = name1;

}

}

Below is the code from the class that I can’t get to take the names from the GameController:

public class name2Controller : MonoBehaviour {

	GameController gameController;
	private string name1;

	// Use this for initialization
	void Start () {

		GameObject varGameObject = GameObject.Find ("Game Manager");
		gameController = varGameObject.GetComponent<GameController>();
		name1 = gameController.name1;
		
		GetComponent<TextMesh>().text = name1;
	
	}
	
}

I have used the debugger in the name2Controller, and it accesses the GameController fine, but it can’t access name1. I literally copied and pasted the code from the Name1Controller into the name2Controller.

Thanks in advance.

wow there is someone out there worse than me on naming classes and variables :slight_smile:

I think your problem might have to do with execution order. Try using Awake in the controller instead of Start()
And ofcource make sure the script is actually in the scene. Made that mistake a few times myself.

When name2Controller is started, your GameManager hasn’t started/instantiated yet. Use logs to see when your GameManager and name2Controller is started.

You should see name2Controller starts before than GameManager.