Apr 062012
 

In this brief tutorial, I wanted to show some quick code examples which will allow your scripts to easily communicate with each other by means of executing each other’s functions.  Without going into descriptions of more intermediate topics such as classes, methods, or other terminology that might be difficult to understand, what I will do here is basically create two javascript files and two functions within those files.  One of those functions will send a message to the other and our desired effect will be achieved.

In the following case, all we are doing is sending a “print” line, which will appear in your unity console.

Script1:

function PrintText(text : String) {
print(text);
}

Script2:

function DoText() {
var target : GameObject = GameObject.FindGameObjectWithTag("myObject");
target.SendMessage("PrintText", "This text was sent and executed!");
}

As you can see from script 2, we’re targeting a game object with the tag of “myObject”.  Creating and adding a tag to any type of gameObject will suffice, so create a cube and be sure to apply the tag you create.  Once finished, just attach script1 to the object.

As for script2, we can trigger this any way we like.  You can choose to add it to an input button or an event to test it, or simply add it to a second gameObject in play and relocate the code into the “Start” section of the script, so it would look something like this:

function Start() {
var target : GameObject = GameObject.FindGameObjectWithTag("myObject");
target.SendMessage("PrintText", "This text was sent and executed!");
}

Be sure this script is attached to an object, or else it will not run as intended when you test the game.  If everything worked correctly, you should get something like this:

There are obviously much more useful ways to use the SendMessage() function, and knowing the basics, you should experiment with things like damage application or sound triggers – really whatever you can think of.  The important thing to note is that because you are targeting the object itself, the command WILL execute all instances of the script you name when calling SendMessage.  This can cause you errors if you didn’t plan for it, so be sure to stay vigilant in its usage.

 

 Leave a Reply

Connect with Facebook