Unity的sendmessage用法


剛學完sendmessage用法,自己也嘗試測試了一下,用法如下:

1.在unity2017新建一個場景test

2.在場景中添加一個立方體cube作為主角,另添加一個膠囊體capsule,調整為如圖形狀作為被調用方。

3.給主角添加腳本test.cs

 1 /***
 2  * 
 3  * 
 4  * 
 5  * 1.測試sendmessage用法
 6  * 2.添加一個button,用於開啟傳值
 7  * 
 8  */
 9 using System.Collections;
10 using System.Collections.Generic;
11 using UnityEngine;
12 
13 public class Test : MonoBehaviour {
14     public GameObject ReceiveObj;
15     void Start()
16     {
17         ReceiveObj = GameObject.Find ("Capsule");
18     }
19     void OnGUI()
20     {
21         if (GUI.Button(new Rect(30,30,50,20),"點擊")) {
22             //調用其他腳本的數據
23             ReceiveObj.SendMessage("DisPlayContent","I'm Hevin!");
24         }
25     }
26 }

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!");}}}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM