Unity Scripting: Sending messages

Unity Scripting: Sending messages

Postby BenChang » Wed Feb 11, 2015 6:03 pm

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);
   }
}
User avatar
BenChang
 
Posts: 176
Joined: Mon Jan 17, 2011 4:48 pm

Return to Game Development

Who is online

Users browsing this forum: No registered users and 1 guest

cron