- Home /
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 :/.
Answer by HarshadK · Oct 06, 2014 at 08:43 AM
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.
Your answer
Follow this Question
Related Questions
RigidBody2D rotation on y-axis not z-axis 1 Answer
Using Layer Filter Raycast 0 Answers
Endless 2D background 4 Answers
Texture2D Power of 2 0 Answers
Crushy Bird Game Doubt 1 Answer