Okay, I have a javascript in one object, and another script in another object.
I want them to talk.
How do you:
Change a public variable in another script/object?
Access a function in another object, or even the same function in another script file.
Cause events based on communication in another script. Pretty much the above item.
Generally, I need scripts and objects to talk to each other, and have NO idea how it would be done. If any answers could be offered in javascript, I would be appreciative.
You declare a variable in one object, using the script name in the other object as its type:
var oScript: OtherObjectScript;
Then, select the first object in the hierarchy, and in its inspector, you should see a variable for OtherObjectScript. Drag the other object that has the script attached into that slot, and it will link to that script.
Talker.JS
public var master : String = "test";
public var oScript: TListener;
function Update ()
{
Talker ("Yay") ;
}
function Talker (test1 : String)
{
oScript.TListener (test1);
}
and
TListener.JS
var slave : String;
function TListener (test1 : String)
{
var test2 = test1;
print(test2);
}
Now, I figured out how to drop the link from Cube2 onto the oScript entry in Inspector, and it works.
Now, How do I automate the designation of oScript, so that when I create objects in code they can be linked up too?
Or would the objects have to send their ‘pointer’ themselves to a global variable database, so it coul be accessed later?
// Set foo DoSomething on the target variable assigned in the inspector.
var target : OtherScript;
function Update () {
// Set foo variable of the target object
target.foo = 2;
// Call do something on the target
target.DoSomething(“Hello”);
}
However, how do I do this when “OtherScript” is a .cs C# script?
When OtherScript is a C# script, I get:
The name ‘OtherScript’ does not denote a valid type.
Is there a work-around? Or, what am I doing wrong?
Use UnityEvents. They let you set up a lot of communication in the Inspector view, which reduces the amount of code you need to maintain. JoeStrout put together a good tutorial video here.