- Home /
Question by
Major · Aug 10, 2012 at 12:22 AM ·
guigameobjectkilldead
Access Var From Another GameObject
i need to access a variable from another game object. what i wan't to happen is have a variable called kills go up by 1 every time the dead function is called by the script controlling the enemy prefab. here's my script(javascript).
Health script for enemy:
var Health : int = 1;
var Type1Damage : int = 1;
var Type2Damage : int = 5;
var Type3Damage : int = 10;
var Blood : Transform;
function Start ()
{
}
function LateUpdate()
{
if(Health <= 0)
{
Health = 0;
Dead();
}
}
function OnCollisionEnter(collision : Collision)
{
if(collision.gameObject.tag == "Type 1")
{
Health -= Type1Damage;
}
if(collision.gameObject.tag == "Type 2")
{
Health -= Type2Damage;
}
if(collision.gameObject.tag == "Type 3")
{
Health -= Type3Damage;
}
}
function Dead()
{
Destroy(gameObject);
Instantiate(Blood, transform.position, transform.rotation);
}
GUI script for camera:
public var Kills : int = 0;
function Update ()
{
}
function OnGUI()
{
GUI.Label(Rect(Screen.width / 2, 10, 60, 20), "" + Kills);
}
Comment
Best Answer
Answer by Seth-Bergman · Aug 10, 2012 at 02:06 AM
make it static:
static var Kills : int = 0;
then access it by the name of the script:
function Dead()
{
HealthScriptName.Kills++;
Destroy(gameObject);
Instantiate(Blood, transform.position, transform.rotation);
}
otherwise, you could create a var to store the player script:
var healthScript : HealthScript;
function Start(){
healthScript = GameObject.Find("Player").GetComponent(HealthScript);
}
then you access it with that:
healthScript.Kills++;
i can't believe it was that simple. i fill like an idiot to think i had to use .getcomponent. :)
Be careful about using static; it means that there is only one instance of the variable. In most cases you should use GetComponent.