unity 3d student

Beginner B28 โ€“ SendMessage() to Call External Functions

How to use SendMessage() to call functions in scripts attached to other objects.

Code Used (Javascript) – Reactor.js

var downTexture : Texture2D;
  1.  
  2. function React () {
  3.  renderer.material.mainTexture = downTexture;
  4.  yield WaitForSeconds(1);
  5.  gameObject.AddComponent(Rigidbody);
  6. }

Code Used (Javascript) – Switcher.js

function OnCollisionEnter(col : Collision) {
  1.  if(col.gameObject.name == "Switch"){
  2.   gameObject.Find("Block").SendMessage("React");
  3.  }
  4. }

Further Reading

Share via Social Media

  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • Add to favorites

39 Comments

    Wow!
    New tutorial!
    Thanks, man.

  • Awesome, new stuff coming as promised !

    Thank you for your hard work and dedication, these videos are really precious!

  • Wow! New video! Thanks, this was so helpful. Please post more videos, i love yours.

  • The goodness just keeps on coming!

  • How processor heavy is this? The Find() function is quite chewy, IIRC, and if SendMessage() has to search every script, that could take some time, too.

    What if you have more than one React() function?

    Anyways, thanks for more videos and keep up the good work! I may actually use Unity for something constructive soon, rather than just playing with it.

  • Might seem trivial but would it not make more sense to put the switcher script onto the switch and tell it to look for a collision with the ball?

    • i was thinking that, as the switch is operating the cube no? and the ball operating the switch.. trivial like you said.

      Great videos though. clearest and most accessible tutorials i have come across by a mile.

    Great tutorial and it’s exactly what I was looking for.
    Thanks!

  • wow
    thanks, man
    you helped me a lot xD

    I’m Wesllei directly from Brazil

  • Brilliant stuff mate; I’m loving your very helpful and concise tutorials.
    I desperately needed this one in particular as I was using an overly complex system where I held a static array of Strings to pass commands to objects, pushed commands like “Camera=Follow”, and then disassembled the strings in a for loop in the receiver script ๐Ÿ˜€
    This is much neater and much more efficient, so thank you!

  • Wow that was super useful, thank you!!!!!!!!

  • Actually i’m using GetComponent to get the script component and call an external function, is SendMessage better to gain performance?

    Thanks.

  • Good and clear tutorial. Explained it rather well and thorough.

  • ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๋„์›€ ๋งŽ์ด ๋ฐ›๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค

    • ๋‹น์‹ ์€ ํ™˜์˜

    Very helpful tutorial!
    Question:
    Is there a way to use “gameObject.Find” to reference an object created with a prefab?

    Example:
    I have a prefab named “GamePiece-Yellow”. What I want to do is spawn an object from the prefab and then move it in a direction.
    I can spawn the prefab but when I try to call the function in the script that I have applied to prefab “GamePiece-Yellow” I get a NullReferenceException error using: gameObject.Find(“GamePiece-Yellow”).SendMessage(“movePieceUP”);

    Is this because when the object is created from the prefab it is named: “GamePiece-Yellow(Clone)” ?

    Thanks!
    -TEK

    • Hi Tek, yes indeed, if you want to avoid that issue, make sure you name your object when you instantiate it- for example (javascript)

      var thing : GameObject = Instantiate(prefabRef, position, rotation);
      thing.name = “ExactlyWhatYouWantToCallit”;

      • That worked, thank you Will!

    how would i make a message that is not gameObject๏ปฟ dependent, so if i wanted to put any game object that i assign to it….like,

    var gameObject01 : GameObject; //switch

    var gameObject02 : GameObject; //block

    or the col to something like this…

    function OnCollisionEnter(col : Collision)

    { if(col.gameObject01 == gameObject01.GameObject) { gameObject02.GameObject.SendMeยญssage(“React”); }

    }

    but it doesn’t seem to work…could you help me out thanks..o an by the way i dont do alot of programming so…sorry..

  • […] ย http://www.unity3dstudent.com/2011/02/beginner-b28-sendmessage-to-call-external-functions/ […]

  • Hi,

    The send message example is AWESOME! But what if I have 10 Objects in the scene named “Block”? it seems to only find the first one for some reason ?

    How would I send the message to all of the other blocks with the same name?

    Or do I have to go through and name them Block, Block1, Block2, Block3 etc.. then update the code like

    gameObject.Find(“Block”).SendMessage(“React”);
    gameObject.Find(“Block1”).SendMessage(“React”);
    gameObject.Find(“Block2”).SendMessage(“React”);
    gameObject.Find(“Block3”).SendMessage(“React”);

    The reason Im having trouble with this is what if I have 25 or so Blocks how would I handle this? to send the message to all of them with the same name? or maybe I did something wrong?

    Cheers,
    Zeek

    Ps I love these tutorials keep them coming ๐Ÿ™‚

    • I found Object.FindObjectsOfType in the scripting reference but I don’t understand it to be able to use with the example above to be able to find all of the Blocks with the name Block.

      • See my reply to your original question.

      Just the wrong approach is all. Things like this, make sure you tag them all the same, then use a for loop to iterate the same command for all of them. Something like (javascript) this –

      var blocks : GameObject[] = GameObject.FindObjectsWithTag(“block”);
      for(var theblock in blocks){
      theblock.SendMessage(“React”);
      }

      Here we find everything tagged ‘block’ and then use that array in a for loop, making a variable called theblock to represent the current entry in the array, then for each time we find an entry in the array, we send it a message called React.

      Good luck!

      • Thanks Will ๐Ÿ˜€

        it works perfectly now ๐Ÿ™‚ they all drop its sooo cool I added a bouncy material lol

        Again Thank you Sir ๐Ÿ˜‰

    Very helpfull, thanx a lot. I’ve got a question though. Can we send variables with sendMessage too ? Like react functions get 2 float type variables and we can send them by ref ??

    • Yes, you can send as your second argument for example in a function called ‘eggs’, you can send 5 –
      SendMessage(“Eggs”,”5″);

    i don’t know u bro , but i am glad to call u as my friend , you are awesome

    i from india

  • function OnMouseDown(){
    gameObject.Find(“EscBox(Clone)”).SendMessage(“React”);
    gameObject.Find(“EscBoxExit(Clone)”).SendMessage(“React”);
    gameObject.Find(“EscBoxCancel(Clone)”).SendMessage(“React”);
    }

    function OnMouseEnter () {
    guiText.material.color = Color.yellow;
    }

    function OnMouseExit(){
    guiText.material.color = Color.white;
    }

    Gets me the following error:
    SendMessage React has no receiver!
    UnityEngine.GameObject:SendMessage(String)
    EscBoxCancel:OnMouseDown() (at Assets/Scripts/EscBoxCancel.js:4)
    UnityEngine.SendMouseEvents:DoSendMouseEvents()

    • ‘Has no reciever’ means that You are finding an object that does not have a script containing the function you’ve named ‘React’ attached to it. Add one, and it’ll work!

    In C#:

    using UnityEngine;
    using System.Collections;

    public class Reactor : MonoBehaviour {

    public Texture2D downTexture;

    void react(){
    renderer.material.mainTexture=downTexture;
    StartCoroutine(fall());
    }

    IEnumerator fall(){
    yield return new WaitForSeconds(2);
    gameObject.AddComponent(“Rigidbody”);
    }
    }

  • Sweet tutorial.

    One question though.
    I wanted to get a GUI to pop up after a message is sent, but OnGUI is a every frame thing. I want to use a message to activate a function. How do I do that?

    • Jon – just use a boolean to set whether that part of the GUI is rendered or not. So place your if that makes a button inside another if statement that says ‘if(showGUI==true){ //gui code here }’ for example.

      • Ah. clever… Thanks.

    cool I’ve watched all the tutorials and learned all!!!
    thank you very much again, you are rocks!!!

  • Hi thanks for the wonderful tutorials!
    I have a problem thought, can we use find on a variable?

    I wrote a script as below, but i get a null error.
    When i replace the variable with the actual game object it works.
    Could you help please?

    var Switch : GameObject;
    var Block : GameObject;

    function OnCollisionEnter (col : Collision) {

    if(col.gameObject.name == “Switch”){
    gameObject.Find(“Block”).SendMessage(“React”);
    }

    }

  • First off. Awesome site. These are really professionally done and are giving me a great base to start from. Will be donating soon.

    I’m making a platform game and want to add a rigidbody to my player when Fire1 is pressed so the bombs fired can interact with the player, pushing the player around. Using this tutorial I can send a message to the player, and the rigidbody is applied. But the character seems to get locked into a gravity glitch. I believe it is because the platform controller has a gravity and the rigidbody has a gravity.

    Is there a way to remove the rigidbody after a certain period of time. Like a removeComponent feature?

    Pseudo Script:
    yield WaitForSeconds(2);
    gameObject.removeComponent(Rigidbody);

    Also can I send a message to apply a rigidbody with the rigidbody gravity option already turned off? Something like what you did with the light tutorial and the light intensity.

    Pseudo Script:
    gameObject.AddComponent(Rigidbody).gravity = false;

    I believe this will fix my gravity glitch.

    Thanks in advance for any help.

    Jeff

  • As always, a nice and simple tutorial. But I think it’s quite essential to mention how you call a function directly, in the event that you might call many external functions.
    A couple of months back, when I first started to learn Unity, I made a character in a 2d game, out of a cube, and had a plane on top of it, as a child. Then I had a script on the plane to animate a new spritesheet everytime a new situation occured, and I would simply send a message from the script on the box, to say what animation should play… Every frame… And then I tossed it on my iPhone… Ouch!
    Turns out, the SendMessage function is about 200 times slower than the direct call on the iPhone…

    Anyways – thanks for a bunch of great tutorials here!

  • You should add the textures, so we the learners can download them and follow the tutorial step by step!

Leave a Comment