- Home /
Access variable from another script? Health!
Ok so i use those two scripts below. One creates a GUI box which displayers the health of the player and the other one is the trigger of the floor that will also make falling damage possible. Unfortunately when the player lands on the trigger i get: "Object reference not set to an instance of an object". How can i correctly access my curHealth var?Thanks!
var curHealth : int = 100;
var maxHealth : int = 100;
function OnGUI(){
GUI.Box(new Rect(20,20,80,40), curHealth + "/" + maxHealth);
}
function OnTriggerEnter(other:Collider){
var otherScript: FallingDamage = GetComponent(FallingDamage);
otherScript.curHealth -= 10;
}
Answer by xKroniK13x · Apr 20, 2013 at 12:40 AM
I do it like this most of the time...
var otherScript : FallingDamage = GameObject.Find("GameObjectName").GetComponent(FallingDamage);
Replace GameObjectName with the name of the game object that contains the script.
However, if this is all contained in the same script, you can simply just access the variable with curhealth -= 10;
Answer by RandomDeveloper · Apr 20, 2013 at 12:56 AM
Maybe like this :
//otherscript.js
var health : int;
var Maxhealth : int = 100;
function Start (){
health = Maxhealth;
}
function Ouch (damage : int){
damage -= health;
}
//groundscript.js
var player : GameObject;
var FloorDamage : int = 40;
function OnTriggerEnter(other:Collider){
player.GetComponent(otherscript).Ouch (FloorDamage);
}
I use this kind of thing a lot.
Good code excerpt for him. Remember, OP, if you use this, when you put groundscript.js
on an object, you then have to assign player
in the inspector window for it to work.
Answer by Brian-Kehrer · Apr 20, 2013 at 12:36 AM
you want this, if the script is attached to the other object
var otherScript: FallingDamage = other.gameObject.GetComponent(FallingDamage);
You should also check for null.