Talking to a variable in another Script?

Hey guys… I get this error when I play my game even though it works fine. But when I build and run I get a crash. If anybody can see some error in my script regarding line 3 I’d love to hear it. Cheers!

The problem is in line 3

UnityException: You are not allowed to call this function when declaring a variable.
Move it to the line after without a variable declaration.
If you are using C# don’t use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function.

I’m trying to alter a variable in another script on another object, are there some other way to do that?

// this is a script on playerReds trigger
public var livesRed : int = 5;
var someScript : s_livesBlue = GetComponent (s_livesBlue);
var heightR : float;

function OnGUI  () 
{
GUI.Label (Rect (10, heightR, 100, 20), "Red Lives: " +livesRed);
}

function OnTriggerEnter(other : Collider)
{
	if(other.gameObject.tag == "playerBlue")
	{	
		livesRed--;	//takes life from playerRed
		someScript.livesBlue++;  //adds life to playerBlue
		audio.Play();	//play the audio attached
	}
}

function Update()
{
	if(livesRed == 0)
	{
		Application.LoadLevel(0);
	}
}
var TheScript: ScriptName = gameObject.Find("GameObjectName").GetComponent("ScriptName");
TheScript.variable = 1;

is one way to do it. :wink:

Not sure if it works outside a function??

though just as a kick off.

function Update() {
var TheScript: ScriptName = gameObject.Find("ObjectName").GetComponent("ScriptName");
TheScript.variable = 1;
if(ImAwesome){
  TheScript.variable = 0;
}
}

just an example :stuck_out_tongue:
cause im not really sure if you can do a call from outside a function, but hey it works.

It doesn’t have to be in a function.

If you’re looking for a gameobject and its script every frame, it makes more sense to keep a reference of it somewhere. Just look for it once in Start().

edit: declaration can be outside, but initialisation usually needs to be inside a function.

thanks guys! your 2nd example works perfect Narfix… Cheer!! :smile: