Delegates, Events and singletons with unity3d–c#

Source: Internet
Author: User
Tags event listener

??

Here I'll show you how to create delegates, events, and singletons to work together. This tutorial is written for Unity3d.


I want to know why.
as a young self-taught programmer, I often find myself writing tons and Boolean statements to determine if some event or action has occurred. I listen to these events to return values through the Coroutines synergistic program and other methods. If you find yourself doing just as well, stop!

Welcome to Events ...

Introduced
recently, I've been trying to improve my C # programming skills and find myself lacking knowledge to understand the fundamentals of events. So, while looking through many tutorials on MSDN and other blogs, discover the most tutorials to be complex and lush with confusing code that is irrelevant to the core concepts. I don't want this to happen to you!

That said I would try to explain the events and the basics of how to use them in the project ...

Singleton?
If you don't know what Singleton,. Single people are not able to-or repeat the script. well ..... .

I recommend the use of Singleton does not need to copy things multiple times in the game. such as inventory system inventory systems. Normally, players only need one inventory and we only want one. When we call it, we want to make sure it doesn't get copied.

There are many ways to create singletons, but this approach is often used because it is simple ...

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 the this is public so we can access it through our Instance.          public void DoSomething () {}           ...  

here, the ' Clicker ' class is attached to my camera. This class handles clicks in 3D space raycast.

To access my ' dosomething ' method from another script, I can only ...

This eliminates the need to use a large number of static methods and variable calls, plus just give us an instance!


Delegates and events?
a delegate can be thought of as a reference pointer to an object. when it is called, it notifies all methods that refer to the delegate.

So the first thing ...

Defines a delegate and gets the method that it fires when called ...

public class Clicker:monobehaviour {   //Event Handler public   delegate void Onclickevent (Gameobject g);   public event Onclickevent OnClick;

the proxy call ' Onclickevent ' through a ' gameobject ', which we can use to define what game object it comes from. We then define the ' event ' OnClick to get the delegate that was invoked when the call was made.

now, in the same script, we need to invoke the delegate and pass it to our game object. by 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.mouseposi tion);          Raycast hit raycasthit hit;          if (Ray, out hit, physics.raycast))     {       //If we click it       if (input.getmousebuttonup (0))       {         // Notify of the event! OnClick (Hit.transform.gameObject);}}}   

As you can see, if Ray is contacted and we left mouse click on the object, we call the event and pass the game object.

The last thing we have to do is refer to the delegate from the other script we are listening to. for this I created a class named Goldpile.

public class Goldpile:monobehaviour {   //Awake   void Awake ()   {     //Start the event listener Clicker.insta nCE. 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;}}}   

In our Awake () method, we define our listening event and assign a local method that gets the call OnClick. ' OnClick ' does not require us to delegate the same method, but it can.

Note: In previous posts we added a singleton to our Clicker class. This allows us to use clicker.instance

As you can see we also created the OnClick () method that passes us to the game we clicked.

Note: If you must use if (g = = gameobject), otherwise it hides the method and other instances in the scene ... This is why we use Gameobject for reference!

Now you are free if you need to add this method to any other script in your game. Don't forget to define the method and delegate in your Awake ().


Yes, best-by-use onenable/ondisable:

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

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

Delegates, Events and singletons with unity3d–c#

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.