Accessing other scripts functions / values

Hi,

I created 2 scripts “A” and “B”, each one attached to different gameobjects. Scripts A has now a function like “test()” and I would like to call this “test” function from the script B. Now my question: What is the preferred way to do this?

Can I access from B the A.test() function by doing something like this?

getComponent(“Name of A gameobject”).test();

I’m having a bit of problems understanding how to call a script function. What I understood so far is that a script needs to be attached to a game object before I can execute an function of that script, is that right?

Thanks,
Martin

GetComponent is a member of GameObject so you have to get a reference to the script like this

var scriptObject: Object = theGameObject.GetComponent("myScript");
scriptObject.Test();

you may need GameObject.Find(“name”); if you dont have a reference to the GameObject.

Yep. You can use an empty game object for this purpose if you want, if you just need a script on something. Typically something like that is done for game managers. Although you can use any object that’s always in the scene, like the main camera or something…doesn’t really matter. Probably the most straightforward, assuming that the script called “ScriptName” is attached to the object called “SomeObject”:

var someScript : ScriptName = GameObject.Find("SomeObject").GetComponent(ScriptName); 
someScript.Test();

You can also assign the object’s script manually. If you write:

var someScript : ScriptName;

function Start() {
	someScript.Test();
}

Then you drag the object with the script “ScriptName” attached to it onto the slot “someScript” in the inspector.

Also, you can set a static variable in SomeScript to itself so you don’t have to get a reference at all:

static var use : ScriptName;

function Awake() {
	use = this;
}

function Test() {
	// Stuff here....
}

This way, anytime you want to refer to a function in ScriptName, just do “ScriptName.use”, like so:

ScriptName.use.Test();

Just make sure that “use” is defined first. Which is to say, never refer to “use” in any other Awake function.

–Eric

Awesome, thanks for the explanations. That clears up a lot of questions I had. Thanks for that!

(I’m sure I’ll be back soon with new questions… :-))