刚学完sendmessage用法,自己也尝试测试了一下,用法如下:
1.在unity2017新建一个场景test
2.在场景中添加一个立方体cube作为主角,另添加一个胶囊体capsule,调整为如图形状作为被调用方。
3.给主角添加脚本test.cs
/***
*
*
*
* 1.测试sendmessage用法
* 2.添加一个button,用于开启传值
*
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine; public class Test : MonoBehaviour {
public GameObject ReceiveObj;
void Start()
{
ReceiveObj = GameObject.Find ("Capsule");
}
void OnGUI()
{
if (GUI.Button(new Rect(,,,),"点击")) {
//调用其他脚本的数据
ReceiveObj.SendMessage("DisPlayContent","I'm Hevin!");
}
}
}
4.给capsule添加Receive.CS,用于接受主角的参数传递,实现自身旋转以便更好观察效果
using System.Collections;
using System.Collections.Generic;
using UnityEngine; public class Receive : MonoBehaviour {
private bool IsRotate = false;
void DisPlayContent (string content) {
print ("Capsule receive a message" );
IsRotate = true;
}
void Update()
{
if (IsRotate) {
this.transform.Rotate (Vector3.up);
}
}
}
5.测试结果,点击按钮,胶囊体开始旋转,sendmessage用法测试完成。
/*** * * * * 1.测试sendmessage用法 * 2.添加一个button,用于开启传值 * */using System.Collections;using System.Collections.Generic;using UnityEngine;
public class Test : MonoBehaviour {public GameObject ReceiveObj;void Start(){ReceiveObj = GameObject.Find ("Capsule");}void OnGUI(){if (GUI.Button(new Rect(30,30,50,20),"点击")) {//调用其他脚本的数据ReceiveObj.SendMessage("DisPlayContent","I'm Hevin!");}}}