Delegates, Events and Singletons with Unity3D – C#

在这里我将演示如何创建代表、 事件和Singletons 在一起工作。本教程为 Unity3D 编写。

我想知道这为什么?

欢迎光临Events事件……

介绍

这样说过我会试着解释Events 事件和在项目中如何使用它们的基础……

Singleton?

有许多方法可以创建Singletons,,但这种方法经常使用,因为它很简单……

// This class sits on my camera and handles all the clicks I send with a Raycast public class Clicker : MonoBehaviour {// Singletonprivate static Clicker instance;// Constructprivate Clicker() {}// Instancepublic static Clicker Instance{get{if (instance == null) instance = GameObject.FindObjectOfType(typeof(Clicker)) as Clicker;return instance;}// Do something here, make sure this is public so we can access it through our Instance.public void DoSomething() { }…

所以,第一件事……

定义一个委托和获取调用时它触发的方法……

public class Clicker : MonoBehaviour { // Event Handler public delegate void OnClickEvent(GameObject g); public event OnClickEvent OnClick;

public class Clicker : MonoBehaviour { // Event Handler public delegate void OnClickEvent(GameObject g); public event OnClickEvent OnClick;// Handle our Ray and Hit void Update (){// Ray Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);// Raycast Hit RaycastHit hit;if (Physics.Raycast(ray, out hit, 100)){// If we click itif (Input.GetMouseButtonUp(0)){// Notify of the event! OnClick(hit.transform.gameObject);}} }}

如你所见的,如果Ray 已联系 ,我们左鼠标单击对象,我们调用该事件并传递游戏物体。

我们必须做的最后一件事是从我们正在听call 的其他脚本引用委托。为此我创建了一个名为 GoldPile 类。

public class GoldPile : MonoBehaviour { // Awake void Awake () {// Start the event listener Clicker.Instance.OnClick += OnClick; }// The event that gets called void OnClick(GameObject g) {// If g is THIS gameObjectif (g == gameObject){ Debug.Log("Hide and give us money!");// Hide gameObject.active = false;} }}

正如你所看到的我们还创建了传递我们点击我们游戏的 OnClick() 方法。

现在你有空,如果需要将此方法添加到您的游戏中的任何其他脚本。别忘了定义的方法,并在你的 Awake() 委派。

Yes, best way is to use OnEnable/OnDisable:

void OnEnable { Clicker.Instance.OnClick += OnClick; }

void OnDisable { Clicker.Instance.OnClick -= OnClick; }

这一秒不放弃,下一秒就会有希望。

Delegates, Events and Singletons with Unity3D – C#

相关文章:

你感兴趣的文章:

标签云: