Page 1 of 1

Unity Scripting: Sending messages

PostPosted: Wed Feb 11, 2015 6:03 pm
by BenChang
The SendMessage() function is a flexible way of communicating between components on the same gameobject, or between different gameobjects, without having to explicitly use GetComponent(). The benefit is that with GetComponent() you must know the explicit type of the component you want to communicate with, whereas SendMessage() doesn't care. It will send the message to any component with a method that matches, no matter what the type is.

Code: Select all

// SenderScript.cs
using UnityEngine;
using System.Collections;

public class SenderScript : MonoBehaviour {
   public GameObject receiver;
        public string message="hello world";
   void Start () {
   
   }
   
   void Update () {
      if (Input.GetKeyDown (KeyCode.A))
      {
         receiver.SendMessage("MyFunction",message);
      }
   }
}


Code: Select all
//ReceiverScript.cs

using UnityEngine;
using System.Collections;

public class ReceiverScript : MonoBehaviour {

   void Start () {    }
   void Update () {    }
   
   void MyFunction (string msg)
   {
      Debug.Log (msg);
   }
}