Unity Scripting: send message with a custom object

Unity Scripting: send message with a custom object

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

SendMessage is limited to one parameter. If you need to send more, you can use a struct, class or array. Here's how to use a class.


Code: Select all
using UnityEngine;
using System.Collections;

// this attribute makes the class something that can show up in the inspector like any other public variable
[System.Serializable]
public class MyData {
   public string foo;
   public float bar;
}

public class SenderScript : MonoBehaviour {
   public GameObject receiver;
   public MyData data;

   void Start () {
   
   }
   void Update () {
      if (Input.GetKeyDown (KeyCode.A))
      {
         receiver.SendMessage("MyFunction",data);
      }
   }
}



Code: Select all
using UnityEngine;
using System.Collections;

public class ReceiverScript : MonoBehaviour {
   void Start () {     }
   void Update () {   }
   
   void MyFunction (MyData d)
   {
      Debug.Log (d.foo);
      Debug.Log (d.bar);
   }
}
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