Sending Messages Between Objects in Unity3D

Something you have to do a lot in games is have to objects communicate with each other. In Scratch, you just have to use the Your message here block. However, in Unity 3DIt’s not as obvious. That was a bit of a problem for me, so I looked around in the coding reference until I found this function.

/*What you need are two objects, each with
their own JavaScript
I used a sphere and a cube.
*/
//In the sphere's JavaScript:
SendMessage ("YourMessageHere", 2);

//In the cube's JavaScriptfunction YourMessageHere (rotation : float)
  transform.Rotate(0, 0, rotation);
}

Let’s depict this method like a schoolroom. Your bud Arnold sends you a paper airplane with the words “YourMessageHere, 2”. You and Arnold just happen to have a secret code in case the school bully intercepts these messages, and the word YourMessageHere just happens to mean “Spin around in a circle, attracting attention while I put the class pet that I found in the waste bin back on teacher’s desk”.

You however, have no clue what speed or direction to spin at. You look back at your comrade’s message and see the number 2.

Ah! your supposed to spin on the Y axis at the speed of two.

Now, that scenario is very ridiculous, and you would probably end up in detention writing lines, but at least your class pet, Chester the Rabbit, would get back to his owner.Bunny

On a shorter, and a lot less juvenile approach, it basically tells anyone who’s listening to do something.

Hope this helps you! Smile

Tags: , , , , , ,

Have something to say?