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


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

     三个物体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就停止旋转了。这个就是事件的委托和监听,他可以作为一个物体交互多个物体的方式

  • 相关阅读:
    【Linux】linux系统管理---好用的一些开源工具
    【转载】超级系统工具Sysdig,比 strace、tcpdump、lsof 加起来还强大
    Redis 主从复制
    Redis 持久化之RDB和AOF
    Redis 快速入门
    EasyUI 树菜单
    Nginx 搭建图片服务器
    vsftpd 安装
    Nginx 安装部署
    Mybatis3 快速入门
  • 原文地址:https://www.cnblogs.com/cindyOne/p/3041471.html
Copyright © 2020-2023  润新知