纳金网

标题: 物体与物体之间的消息传递(二) [打印本页]

作者: 刀锋狼    时间: 2014-4-30 03:28
标题: 物体与物体之间的消息传递(二)
除了上一节所说的方式外,物体之间的消息传体还可以用事件委托的方式。
三个物体AA,BB,CC
AA上挂了一个委托事件的脚本
  1. using UnityEngine;
  2. using System.Collections;

  3. public class DelegetEvent : MonoBehaviour {

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

  12.     // Use this for initialization
  13.     void Start () {
  14.     }
  15.     // Update is called once per frame
  16.     void Update () {
  17.      
  18.     }
  19. }
复制代码
BB和CC都挂上事件监听的脚本
  1. using UnityEngine;
  2. using System.Collections;

  3. public class ListenEvent : MonoBehaviour {


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

  12.     void de_MouseOver(GameObject obj)
  13.     {
  14.         this.transform.Rotate(new Vector3(0,1,0)); //物体旋转
  15.         Debug.Log(obj.name);
  16.     }
  17.      
  18.     void Update () {
  19.      
  20.     }
  21. }
复制代码
点击运行后,只要鼠标离开AA物体,BB和CC物体都会旋转了。移到AA物体上,BB和CC就停止旋转了。这个就是事件的委托和监听,他可以作为一个物体交互多个物体的方式

作者: hyui    时间: 2014-4-30 03:55
Thank you for sharing! ) ) )




欢迎光临 纳金网 (http://course.narkii.com/club/) Powered by Discuz! X2.5