Delegates, Events and Singletons with Unity3D – C#

??

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

我想知道这为什么?
作为一个年轻的自学程序员,我经常发现自己写tons 和布尔的语句,以确定是否发生了某些event 或action 。我听这些events 事件通过Coroutines 协同程序和其他方法来返回值。如果你发现自己这做得一样好,停下来 !

欢迎光临Events事件......

介绍
最近,我一直要改善我的 C# 编程技能,以及发现自己缺乏知识,了解Events事件基础。所以,虽然通过许多教程在 MSDN 和其他博客上看着,发现了大多数的教程要复杂和茂盛用令人费解的代码不相关的核心概念。我不希望这发生在你身上 !

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

Singleton?
如果你不知道什么Singleton,。单身人士是不能 — 或重复的脚本。嗯......。

我推荐使用Singleton不需要复制多次在game中的东西。如Inventory System库存系统。通常情况下,玩家只需要一个库存,我们只想要一个。当我们调用它时,我们想要确保它不会得到复制。

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

// This class sits on my camera and handles all the clicks I send with a Raycast
public class Clicker : MonoBehaviour
{
     // Singleton
     private static Clicker instance;   

     // Construct
     private Clicker() {}    

     // Instance
     public 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() { }
         ...  

在这里,‘Clicker’ ‘类附加到我的Camera上。此类处理点击 在3D 空间Raycast 的 。

若要从另一个脚本访问我 ‘DoSomething’  的方法,我只能...

Clicker.Instance.DoSomething(); 

这消除了需要使用大量的静态方法和变量的调用,再加上只给了我们一个实例 !

委托和事件?
委托可以看作是对对象的引用指针。当它被调用时,它会通知所有引用该委托的方法。

所以,第一件事......

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

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

代理调用 ‘OnClickEvent‘ 通过一个‘GameObject’,我们可以使用来定义它来自什么游戏物体。然后,我们定义了 ‘event’  OnClick 获取调用时调用的委托。

现在,在相同的脚本中,我们需要调用委托,并将其传递我们的游戏对象。通过 Raycast......

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 it
       if (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 gameObject
     if (g == gameObject)
     {
 Debug.Log("Hide and give us money!");

       // Hide
 gameObject.active = false;
     }
   }
}

在我们的 Awake() 方法中,我们定义我们listening 的事件并分配一个获取调用 OnClick 的本地方法。‘OnClick‘ 不需要我们委托方法相同,但它可以。

注:在以前的帖子我们添加一个单例到我们Clicker 类。这使我们能够使用 Clicker.Instance

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

注:如果您必须使用 if (g == gameObject),否则,它将隐藏该方法以及场景中的其他实例...这就是为什么我们通过GameObject 供参考 !

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

Yes, best way is to use OnEnable/OnDisable:

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

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

时间: 2024-08-17 05:11:51

Delegates, Events and Singletons with Unity3D – C#的相关文章

Delegates, Events and Lambda Expression

The content and code of this article is referenced from book Pro C#5.0 and the .NET 4.5 Framework by Apress. The intention of the writing is to review the konwledge and gain better understanding of the .net framework.    Up to this point, most of the

C#心得与经验(三)Regex,Exception,Delegate & Events

一.Regular Expression using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace RegexTest { class Program { static void Main(string[] args) { str

Lambda 表达式(C# 编程指南) 微软microsoft官方说明

Visual Studio 2013 其他版本 Lambda 表达式是一种可用于创建委托或表达式目录树类型的匿名函数. 通过使用 lambda 表达式,可以写入可作为参数传递或作为函数调用值返回的本地函数. Lambda 表达式对于编写 LINQ 查询表达式特别有用. 若要创建 Lambda 表达式,需要在 Lambda 运算符 => 左侧指定输入参数(如果有),然后在另一侧输入表达式或语句块. 例如,lambda 表达式 x => x * x 指定名为 x 的参数并返回 x 的平方值. 如下

(转) 将VB.NET网站转换成C#的全过程

在学习URL重写过程中碰到个是VB写的源码,看起来总是不爽的就GOOLE了下 感觉这个文章写的不错 原文地址 http://www.cnblogs.com/cngunner/archive/2006/01/16/318309.html 前两天看到一个比较不错的网站,可惜是用vb.net写的,俺弄不大明白,于是心血来潮想把它全部转换成C#代码的.花了N长时间,问了几多人,费了不少神,总算是能让网站在C#下马马虎虎的跑了,不小心还喜欢蹦出个鲜红夺目的错误信息,真是让人战战兢兢. 总结的经验教训就是:

VB与C#的区别(转载)

由于工作原因要熟悉这两门编程语言.网上找的. VB.NET Program Structure C# Imports System             Namespace Hello               Class HelloWorld                   Overloads Shared Sub Main(ByVal args() As String)                      Dim name As String = "VB.NET"  

Event Manager and Event Listener

?? 我已经读完关于事件的文件,看着一对夫妇的教程,但是还有一些我仍然不握.在我见过的Event Managers事件管理器示例,将触发该事件的方法是在同一个class 作为事件管理器.喜欢这个: using UnityEngine; using System.Collections; public class EventManager : MonoBehaviour { public delegate void CheckpointHandler(int id); public static

VB.NET and C# 差异

VB.NET Program Structure C# Imports System Namespace Hello    Class HelloWorld       Overloads Shared Sub Main(ByVal args() As String)          Dim name As String = "VB.NET"          'See if an argument was passed from the command line         

【Xamarin笔记】Events, Protocols and Delegates

Events, Protocols and Delegates   事件.协议和委托 This article presents the key iOS technologies used to receive callbacks and to populate user interface controls with data. These technologies are events, protocols, and delegates. This article explains what

Delegates 和 Events 在unity中的使用

?? 如何创建和使用委托Delegates 以提供复杂和动态功能在您的脚本上. DelegateScript .cs using UnityEngine; using System.Collections; public class DelegateScript : MonoBehaviour { delegate void MyDelegate(int num); MyDelegate myDelegate; void Start () { myDelegate = PrintNum; myD