- Home /
Accessing other gameobject's script variables : why doesn't this work?
I have my player (tagged Player), and he has a script, called PlayerStatus.js. In a child object of the player, called projectileLauncher, I'm trying to access the strength variable from the PlayerStatus script on the player, but getting a null reference exception.
Here is the code I'm currently using (simplified) in projectileLauncher.js:
private var player : GameObject; private var strength : int;
function Start(){
player = GameObject.FindWithTag("Player");
strength = player.GetComponent(PlayerStatus).strength;
}
What am I doing wrong?
Answer by Lenn · Dec 29, 2010 at 03:30 AM
Use 'parent' property instead of FindWithTag. I've found that it is far more reliable. Logically too it makes more sense -- being that you're in projectileLauncher a child of player (why go 'looking' for it?).
private var player : PlayerStatus; private var strength : int;
function Start(){
player = transform.parent.gameObject.GetComponent(PlayerStatus);
strength = player.strength;
}
function Start(){ player = transform.parent.gameObject.GetComponent(); strength = player.strength; }
Answer by Cap · Jun 03, 2010 at 11:49 AM
You need to use GetComponentInChildren since the script is attached to a child of the object you're referencing (player). GetComponent will only return components attached to the referenced object directly.
Your answer
Follow this Question
Related Questions
Accessing Other Script Variables (C#) 2 Answers
Can't understand generic getComponent for Js 1 Answer
Script access (without script name) 1 Answer
Stupid question about public / private variables 2 Answers
acces variables from other script 2 Answers