Cannot access variables or method of spawned playerObject

Hello!

I have a script that spawns my player object, and I want to pull out the health of that player, but I’m getting an error saying that it can’t find the variable or method. Here is the code in my object that spawns the player:

    player1 = Instantiate(player) as GameObject;
    player1.transform.position = new Vector3(-9, 0, 0);
	playerHealth = player1.health;

‘health’ is a variable in the player object that is spawned. Unity still think’s its a game object, so it can’t get the health variable. The same thing happens when I try and use a Get/Set method in the player object to do the same thing. It has to be something simple, but I’m not finding out what, and I don’t know what to search :/.

To access the health variable you need to get a reference to the script component which contains your health variable. Something like:

playerHealth = player1.GetComponent<NameOfScript>().health;

Replace the NameOfScript from above line with the name of your script component.