zoukankan      html  css  js  c++  java
  • 物体与物体之间的消息传递(二)

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

     三个物体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安装及入门
    20165103学习基础和C语言基础调查
    20165103 我期望的师生关系
    自旋锁,偏向锁,轻量级锁 和 重量级锁
    volatile的使用及其原理
    (PASS)什么是原子性和原子性操作?
    Linux操作系统 和 Windows操作系统 的区别
    Linux常用命令大全(很全面)
    CAS机制总结
    CAS -- ABA问题的解决方案
  • 原文地址:https://www.cnblogs.com/cindyOne/p/3041471.html
Copyright © 2011-2022 走看看