Calling a variable from another script [SOLVED!]

:smile: Noob Crisis: Averted :smile:
I’m creating an in-game GUI. It works when stuck inside my Player.js script. However, just to keep things nice and modular, I’d like to separate the two. How these stand while separated now is this:

player.js:

@script AddComponentMenu( "Entities/Player" )
@script RequireComponent( CharacterController )

// Game Stats...
var hp : int;
var maxhp : int;
var rankTag: String;
var kills : int;
var killsToGo : int;
var potions : int;
var atk : int;
var def : int;

// This is still very basic, much remains to be done.

function Awake()
// When we change maps, the player object
// DOES NOT need to be destroyed!
{
  DontDestroyOnLoad( this );
}

GameGUI.js:

@script AddComponentMenu( "UIs/HUD" )

var me : Player;  // I know this line is DEAD wrong.

function OnGUI()
{
  GUI.Box( Rect( 10,10, 200,20 ), "Health: " + me.hp + "/" + me.maxhp );
}

The errors point me to Line 3 of the GameGUI.js code - this line for certain is completely wrong, but I’m not sure how to make this GUI script look for an associated Player script. I could use some help on this.

http://forum.unity3d.com/viewtopic.php?t=32332
http://answers.unity3d.com/questions/32/how-do-i-call-a-function-in-another-gameobjects-script
http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

Well, that cleared the error! :smile:

@script AddComponentMenu( "UIs/HUD" )

function OnGUI()
{
  // Had to make this *find* the player script
  // object, all well and good!  Also has to be
  // local to the function it's called in,
  // apparently.
  var me : player = FindObjectOfType( player );

  GUI.Box( Rect( 10,10, 200,20 ), "Health: " + me.hp + "/" + me.maxhp );
}

EDIT: Solved fully now! Thank you KaelisAsur, you’re the best thing since waffles!

Not really. :slight_smile:

A ‘better’ piece of code would look like this:

//WARNING -- Browser typed code
@script AddComponentMenu("UIs/HUD")

var me : player;

function Start(){ //gets called once at the beginning of the game
     me = FindObjectOfType(player); //alternatively, you could call GameObject.FindWithTag("Player").GetComponent("player") -- or even just assign it in the unity inspector
}

function OnGUI() 
{ 
  GUI.Box( Rect( 10,10, 200,20 ), "Health: " + me.hp + "/" + me.maxhp ); 
}

Good luck,

-Lincoln Green

Oh, good point.

I saw the warning that FindObjectOfType() is a slow function, the Start() hook is a great way to get around that!

@script AddComponentMenu("UIs/HUD") 

var me : player;

function Start()
{
  // Reference to the player entity script.
  me = FindObjectOfType( player );
}

function OnGUI()
{
  GUI.Box( Rect( 10,10, 200,20 ), "Health: " + me.hp + "/" + me.maxhp ); 
}

Works beautifully, and now the me reference is global so I can work with it! Thanks, Mr. Green!