1.定义一个委托(委托要与后面的执行函数参数保持相同,也可以不带参数)
2.通过委托 声明一个事件
3.发送方:发送事件
4.接收方:a.执行函数, b.绑定事件
新建C#脚本 fasong,代码如下:
using UnityEngine; using System.Collections; public class fasong : MonoBehaviour { //!!!!定义委托(委托参数要与后面执行函数参数保持一致) public delegate void ListenerHandler(Object sender); //!!!!通过委托 声明一个事件 public event ListenerHandler Listener = null; // Use this for initialization void Start () { } // Update is called once per frame void Update () { //!!!!发送事件 if (Input.GetMouseButtonDown(0))//0为左键,1为右键 { this.Listener(this); } //!!!键盘A监听 if (Input.GetKeyDown(KeyCode.A))//键盘按下A,发送事件 { Listener(this); } } }把脚本挂在其中一个物体上。
接收者人物的脚本修改如下:
using UnityEngine; using System.Collections; //!!!!!!!!!!! using System.Collections.Generic; public class womenRun : MonoBehaviour { private NavMeshAgent agent; public GameObject target; private Animator animator; //!!!!!!!!!!!! public GameObject aaa; // Use this for initialization void Start () { //获取组件NavMeshAgent agent = GetComponent<NavMeshAgent>(); animator = GetComponent<Animator>(); //!!!!!绑定事件 aaa.GetComponent<fasong>().Listener += new fasong.ListenerHandler(noteMe); } // Update is called once per frame void Update () { } //!!!!!执行函数 private void noteMe(Object sender) { Debug.Log(sender.name); //SetDestination自动寻路函数,targer为目标,transform为目标组件,position为组件上位置 agent.SetDestination(target.transform.position); animator.Play("run"); } }上面fasong脚本挂在哪个物体上,则把哪个物体拖到人物脚本上:
