Delegate中文翻译为“委托”。C#语言是支持代理的,并且代理是非常的好用的一种方式。简单的来说就是你委托别人帮你做一件事情,当委托人做完你委托的事情之后会告诉你他做完了。C#中的委托类似于C或C++中的函数指针。使用委托使程序员可以将方法引用封装在委托对象内。然后可以将该委托对象传递给可调用所引用方法的代码,而不必在编译时知道将调用哪个方法。与C或C++中的函数指针不同,委托是面向对象、类型安全的,并且是安全的。
先简单的使用一下Delegate(委托)
直接代码:
代理的声明,在开发中应该有一个专门用来委托的类。
using System.Collections;using System.Collections.Generic;using UnityEngine;public class CubeManager : MonoBehaviour { delegate void CubeMoveHDelegate(); // //委托的标识符就是delegate,LogMessageDelegate(string message)就是委托完毕后回调的方法名称 CubeMoveHDelegate hDelegate; // Use this for initialization void Start () { SmartCube[] cubes = FindObjectsOfType(typeof(SmartCube)) as SmartCube[]; for(int i = 0; i< cubes.Length; i++) { SmartCube c = cubes[i]; hDelegate += c.MoveHorizontal; } } // Update is called once per frame void Update () { if(Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow)) { hDelegate(); } }}使用代理,需要把具体的实现类方法 挂载到相关的gameobject上。
using System.Collections;using System.Collections.Generic;using UnityEngine;public class SmartCube : MonoBehaviour { public float speed = 10; public void MoveHorizontal() { transform.Translate(Time.deltaTime * speed * Input.GetAxis("Horizontal"), 0, 0); }}
新闻热点
疑难解答