zoukankan      html  css  js  c++  java
  • C#中的委托和事件

    委托和事件一般是一起使用的,事件也是特殊的委托,事件和委托的的区别有:

     1.委托可以使用 ‘=’ 来赋值而事件不可以

     2.委托可以在类的外部调用(最好不要),而事件只可以在类内部调用

     3.委托是一个类型,而事件是用来修饰对象的

     委托在U3D中提供了一种脚本之间通信的方式,一般也用来起回调的作用,就像传参数一样,可以传递方法。

    例如声明两个类cube.clsss和sphere.class

     1 using UnityEngine;
     2 using System.Collections;
     3 
     4 public class cube: MonoBehaviour {
     5 
     6     public delegate void deleFunction(GameObject str);
     7 
     8     public static event deleFunction eventFunction;
     9 
    10     // Use this for initialization
    11     void Start () {
    12     
    13     }
    14     
    15     // Update is called once per frame
    16     void Update () {
    17     
    18     }
    19 
    20     void OnMouseOver(){
    21 
    22         if(eventFunction!= null){
    23 
    24             eventFunction(this.gameObject);
    25         }
    26     }
    27 }
    View Code
     1 using UnityEngine;
     2 using System.Collections;
     3 
     4 public class sphere: MonoBehaviour {
     5 
     6 
     7 
     8     // Use this for initialization
     9     void Start () {
    10 
    11         cube.eventFunction += Test;
    12     }
    13     
    14     // Update is called once per frame
    15     void Update () {
    16     
    17     }
    18 
    19     void Test(GameObject t){
    20 
    21         this.renderer.material.color = Color.red;        
    22         t.transform.Rotate(transform.forward);
    23     }
    24 }
    View Code

    在unity中创建cube和sphere,将脚本托给相应物体。运行游戏会发现

    在游戏开始的时候,sphere脚本注册cube产生的委托,来执行Test函数,

    当鼠标移入cube物体上时,会判断时间是否有人注册,如果有人注册会将cube的gameobject传个注册函数并执行sphere里面的注册函数。

    这样做也就实现了用cube的OnMouseOver事件来触发sphere物体的Test函数。

  • 相关阅读:
    iOS--------cocoapods遇到的问题
    NTFS
    交换机配置telnet
    交换机
    华为模拟器配置telnet
    路由器
    OSI模型
    网络拓扑
    为什么CAS加锁是线程安全的?--理解原子操作
    零基础自学编程选哪种语言好?世上最好编程语言推荐
  • 原文地址:https://www.cnblogs.com/baoluqi/p/4339885.html
Copyright © 2011-2022 走看看