Unity 3D Scripting Examples and Exercises: Work Sheet Three

The following example will introduce an important technique of two-way (duplex) script communication using public methods in each script.

This tutorial assumes you have completed worksheet one and two.

Sending messages between scripts.

1. Create a Sphere Object and Cube Object in the environment and name them TransmitSphere and ReceiveCube respectively. Create and add a material to each object.

2. Create a new C# script asset and name it Transmit. Open the script and add the following code as shown in bold below:

publicclassTransmit:MonoBehaviour{
string[]messages=newstring[5];
GameObjectmessageToCube;

//Usethisforinitialization
voidStart(){

3. Add the following method inside the Transmit script’s Start method.

messages[0]="HellofromtheTransmitter";
messages[1]="Youoweme£300!";
messages[2]= "Visitmywebsitetoday";
messages[3]="Yourmailboxisfull"; messages[4]="Youhavewon$3000!replyto collectyourprize!";

messageToCube=GameObject.Find("ReceiveCube");

4. Add the following method after the Transmit script’s Update method.

publicvoidsendMessage(){
stringmessageToSend="";
if(Random.value0.5f){
messageToSend=messages[Random.Range(0,5)];
}

// put this statement all on one line

messageToCube.GetComponentReceiveMessage>().receiveMessage(messageToSend);
}

5. Add the following code inside the Update method

sendMessage();

6. Add the script to the Transmit Sphere

7. Create another new script and name it ReceiveMessage and add the following code after the Update method

publicvoidreceiveMessage(stringmessage){
Debug.Log("Themessageis:"+message);
}

8. Add the script to the ReceiveCube. Also, create another object to act as an interface between the scripts, name it System and attached both scripts to the object.

8.Open the Console Window and run the System. You should see messages appearing in the Console Window relating to the random messages sent from the TransmitSphere being received by the ReceiveCube Object.

Exercises:

1.  Add a variable to the ReceiveMesage script that counts the number of messages received. Display the current number of messages in the Console Window.

2.  Try changing the Random value probablity in the Transmit script to see the effect on the message count.

3.  Add some code in the receive script to do the following:

Change the colour of the ReceiveCube based on the number of total messages received, e.g. 100, 500 and 1000.

4. Think about how to change the size of the ReceiveCube Object as the

number of messages exceed a certain value.

5. Try adding a method in the TransmitSphere that can receive a

message from the ReceiveCube and a method in the ReceiveCube

to send a message to the TransmitSphere Then if the message

count exceeds some value the ReceiveCube sends a message to

the TransmitSphere “Stop Sending Me Messages!”.