(@WhiteTaken)Unity中Invoke的用法

今天无意间读到大神写的代码,看到了Invoke函数,于是产生兴趣。后来才明白自己要学习的东西还有很多。

下面讲用法。

Invoke是延时调用函数,在用Invoke函数之前需要引入命名空间using UnityEngine.Events;

1.Invoke("MethodName",2)

这个比较简单,写在c#脚本中,意为 两秒之后调用一次,MethodName方法。

2.InvokeRepeating("MethodName",1,2)

这个方法就是多次调用Invoke,即理解为一秒后,每隔两秒调用MethodName方法。

3.CancelInvoke("MethodName")

取消MethodName方法的调用。

直接上代码看更加直观。

 1 using UnityEngine;
 2 using System.Collections;
 3 using UnityEngine.Events;
 4 
 5 public class InvokeTest : MonoBehaviour {
 6     public GameObject Prefabs;
 7     private Vector3 v3;
 8     public int i = 5;
 9     // Use this for initialization
10     void Start () {
11         v3 = new Vector3(0, 0, 0);
12         Invoke("TestIns", 1);
13         //InvokeRepeating("TestIns", 2, 1);      //调用InvokeRepeating时候解开
14     }
15     
16     // Update is called once per frame
17     void Update () {
18         if (v3.x == 20) CancelInvoke("TestIns");
19     }
20 
21     void TestIns() {                      
22         //v3.x += i;                    //调用InvokeRepeating时候解开
23         Instantiate(Prefabs,v3,Quaternion.identity);
24     }
25 
26 }

以上代码,分别是Invoke方法,InvokeRepeating方法,CancelInvoke方法的使用。

Invoke还有一个用法就是可以激活UnityEvent。

下面是例子。

 1 using UnityEngine;
 2 using System.Collections;
 3 using UnityEngine.Events;
 4 
 5 public class TestLoader : MonoBehaviour {
 6     [SerializeField]
 7     protected UnityEvent onLoad = new UnityEvent();
 8     [SerializeField]
 9     protected UnityEvent unLoad = new UnityEvent();
10     // Use this for initialization
11     void Start () {
12         Load();
13         UnLoad();
14     }
15     
16     // Update is called once per frame
17     void Update () {
18     
19     }
20 
21     [ContextMenu("Load")]
22     public void Load() {
23         onLoad.Invoke();
24     }
25 
26     [ContextMenu("unLoad")]
27     public void UnLoad() {
28         unLoad.Invoke();
29     }
30 }

这里有两个序列化的UnityEvent,可能看代码不是很直观,直接上图。

      

是不是感觉很眼熟。对就是,像我们经常看到的Button下边的OnClick其实就是这种东西。

我们为这个东西挂上我们自己的测试脚本。

但是这时候我们想要调用测试脚本的方法了,这时候就用到了Invoke。

这里会自动调用UnityEvent下的脚本的指定方法。

测试脚本的代码如下。

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class onLoadScripts1 : MonoBehaviour {
 5     public void systemLoadMessage() {
 6         Debug.Log("=======WhiteTaken=======");
 7     }
 8 
 9     public void systemLoadMessage(int i) {
10         Debug.Log("=====WhiteTaken:" + i + "======");
11     }
12 }
13 
14 using UnityEngine;
15 using System.Collections;
16 
17 public class onLoadScripts2 : MonoBehaviour {
18     public void systemLoadLog() {
19         Debug.Log("--------WhiteTaken----------");
20     }
21 }
22 
23 using UnityEngine;
24 using System.Collections;
25 
26 public class unLoadScripts : MonoBehaviour {
27     public void systemUnLoad(string name) {
28         Debug.Log("===----+ "+name+"卸载:-----=====");
29     }
30 }

运行以后我们可以看到打印结果。

Invoke的其他用法,还没怎么用到,欢迎大家对我提出意见。有错误我会直接修改。

今晚继续学习单例模式。 

原文地址:https://www.cnblogs.com/WhiteTaken/p/6381984.html