Page 1 of 1

Unity Scripting: send message with a custom object

PostPosted: Wed Feb 11, 2015 6:06 pm
by BenChang
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);
   }
}