unity中object 对象之间用c# delegate方式进行通信

unity 3D经常需要设计到不同object之间数据通信和事件信息触发。这里可以利用C#本身的事件和代理的方法来实现。
这里实现了在GUI上点击按钮,触发事件,移动object cube移动的例子。
Main Camera 挂载实现GUI的 Label.cs脚本
Cube挂载 Cube.cs脚本

Label.cs

using UnityEngine;
using System;

// 声明物体移动代理类型
public delegate void EventObjectMoveDelegate(Vector3 dirct);

public class Label : MonoBehaviour {

    private Rect windowRect;
    public event EventObjectMoveDelegate cubeMove;

    void Start()
    {
        windowRect = new Rect(20, 20, 200, 300);
    }

    // Update is called once per frame
    void Update()
    {


    }

    void OnGUI()
    {
        windowRect = GUI.Window(0, windowRect, Mywindowfunc, "windows");
    }

    void Mywindowfunc(int windowId)
    {
        if (GUI.Button(new Rect(10, 20, 100, 20), "moveUp"))
        {
            if (null != cubeMove)
            {
                cubeMove(Vector3.up);
            }            
        }

        if (GUI.Button(new Rect(10, 50, 100, 20), "moveDown"))
        {
            if (null != cubeMove)
            {
                cubeMove(Vector3.down);
            }
        }

        if (GUI.Button(new Rect(10, 80, 100, 20), "moveLeft"))
        {
            if (null != cubeMove)
            {
                cubeMove(Vector3.left);
            }
        }

        if (GUI.Button(new Rect(10, 110, 100, 20), "moveRight"))
        {
            if (null != cubeMove)
            {
                cubeMove(Vector3.right);
            }
        }

        GUI.DragWindow(new Rect(0, 0, 10000, 1000));
    }
}

cube.cs

using UnityEngine;
using System.Collections;
using System;

public class cube : MonoBehaviour {

    // Use this for initialization
    void Start () {

        GameObject.Find("Main Camera").GetComponent<Label>().cubeMove += cubeMoveHandler;
    }
	
	// Update is called once per frame
	void Update () {

    }

    void cubeMoveHandler(Vector3 dirct)
    {
        transform.Translate(dirct);
    }
}

代码地址:
https://github.com/caimagic/Unity_Object_Commucation_With_Delegate.git

posted @ 2016-10-18 14:49  caimagic  阅读(1521)  评论(0编辑  收藏  举报