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

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

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

1014091-20161018144750123-329174135.png

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

转载于:https://www.cnblogs.com/langzou/p/5973257.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值