物体与物体之间的消息传递(二)

除了上一节所说的方式外,物体之间的消息传体还可以用事件委托的方式。

 三个物体AA,BB,CC

 AA上挂了一个委托事件的脚本

using UnityEngine;
using System.Collections;

public class DelegetEvent : MonoBehaviour {

    public delegate void EventHandler(GameObject obj); //委托
    public event EventHandler MouseOver; //事件
    
    void OnMouseOver() { //鼠标离开触发
        if (MouseOver != null) {
            MouseOver(this.gameObject);
        }
    }

    // Use this for initialization
    void Start () {
    }
    // Update is called once per frame
    void Update () {
    
    }
}

BB和CC都挂上事件监听的脚本

using UnityEngine;
using System.Collections;

public class ListenEvent : MonoBehaviour {


    // Use this for initialization
    void Start () {
        //GameObject.Find("CubeSource") 是找到某一个名字为CubeSource的物体
        GameObject obj = GameObject.Find("CubeSource");
        //obj.GetComponent<DelegetEvent>() 找到CubeSource物体上的脚本DelegetEvent
        DelegetEvent de = obj.GetComponent<DelegetEvent>();
        de.MouseOver += de_MouseOver;
    }

    void de_MouseOver(GameObject obj)
    {
        this.transform.Rotate(new Vector3(0,1,0)); //物体旋转
        Debug.Log(obj.name);
    }
    
    void Update () {
    
    }
}

 点击运行后,只要鼠标离开AA物体,BB和CC物体都会旋转了。移到AA物体上,BB和CC就停止旋转了。这个就是事件的委托和监听,他可以作为一个物体交互多个物体的方式

原文地址:https://www.cnblogs.com/cindyOne/p/3041471.html