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;
}
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;
}
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.