Unity Community


Results 1 to 6 of 6

  1. Location
    Austin, TX
    Posts
    751

    Using C# Events with Unity

    I am having a hard time figuring out how to use C# events with my Unity scripts. I'm not that experienced.

    What I would like is to be able to trigger an event when I want and have various scripts in various objects receive the message that the event has been triggered to do stuff of their own.

    Could someone post a generic event handler in C# that I can use as a template for my own code please? I'm looking for something like this:

    In one object we have:
    Code:  
    1. // This script triggers the event:
    2. if(GUI.Button (...))
    3.     {
    4.     // trigger event
    5.     }

    In another object we have:
    Code:  
    1. // This script also triggers the same event:
    2. if(Raycast (...))
    3.     {
    4.     // trigger event
    5.     }

    In another object we have:
    // This function gets triggered by the event:
    Code:  
    1. void TriggerEvent()
    2.     {
    3.     // does stuff
    4.     }

    And yet other objects can also be triggered and do their own thing.

    I'm wading through Daniel Solis' book Illustrated C# 2005 which has enabled me to translate my scripts from JS to C#, but for some reason I'm choking on Events.

    Also, do I have to use another "using System." statement?

    Thank you!
    if (Unity) happiness++;


  2. Location
    New Zealand
    Posts
    89
    Here's a couple of c# event tutorials. You're going to want to understand what's happening if you're going to use c# events or you're bound to have problems.

    http://msdn.microsoft.com/en-us/libr...8VS.71%29.aspx

    http://www.codeproject.com/KB/cs/csevents01.aspx


  3. Location
    Bulgaria
    Posts
    566
    Using System is for C# functionality. Let it be.

    As for your problem I suggest :
    http://www.unifycommunity.com/wiki/i...enger_Extended
    http://www.levelbylevel.com/blog/uni...nger-tutorial/
    (The second link is a tutorial for the messenger)

    Pretty simple to use and pretty handy.


  4. Location
    Austin, TX
    Posts
    751
    After further struggles I used jedybg's out of the box solution, or rather it's predecessor, CSharpMessenger, from the Wiki here:

    http://www.unifycommunity.com/wiki/i...SharpMessenger

    It's just too easy not to use! Perhaps someday when I have more than a week of c# experience under my belt I'll be able to write and use Delegates and Events on my own as needed, but until then this solution will free my time to continue to learn about the basics of object oriented programming.

    Thanks for those links to both of you!!!

    if (Unity) happiness++;


  5. Posts
    8
    I don't know whether it's different within Unity (just come back after a long time away and still only exploring this wonderful software.)

    However, events, C# style:


    Code:  
    1. // Player.cs
    2. namespace PlayerStuff
    3. {
    4.    public delegate void PlayerRespawnedEventHandler(float x, float y);
    5.    
    6.    class Player
    7.    {
    8.        public event PlayerRespawnedEventHandler PlayerHasRespawned;
    9.        private Vec2 m_pos;
    10.  
    11.        public Player(Vec2 pos)
    12.        {
    13.            // Initialise player
    14.            m_pos = pos;
    15.        }
    16.  
    17.        // Lots of player stuff
    18.  
    19.        private PlayerDied()
    20.        {
    21.            // Respawn player
    22.  
    23.            // null check not necessary, but helps
    24.            if(PlayerHasRespawned != null)
    25.            {
    26.               // All listeners will be invoked
    27.               PlayerHasRespawned(m_pos.x, m_pos.y);
    28.            }
    29.        }
    30.    }
    31. }

    Then some other file

    Code:  
    1. // GameEvents.cs
    2.  
    3. namespace GameStuff
    4. {
    5.     class Status
    6.     {
    7.         // Doing stuff
    8.        
    9.         public Status()
    10.         {
    11.            // Get handle to player game object
    12.            
    13.            // Now hook up to event
    14.            playerGameObject.PlayerHasRespawned += new PlayerRespawnedEventHandler(ActOnRespawn);
    15.         }
    16.  
    17.         private void ActOnRespawn(float x, float y)
    18.         {
    19.             // Do the funky chicken.
    20.         }
    21.     }
    22. ]


    The event that Player exposes is of type PlayerRespawnedEvenHandler. This defines the data that will be supplied when the event is called. Our GameStff class wants to know when a player has respawned and so after getting a handle to the instance (will be via a Unity API call, I guess) can hook up to the event. It is effectively saying when the event happens, I'll (GameStuff) do some actions that you (Player) don't need to know about. You could also say Player has delegated some work away from itself, but given the paradigm, it's verging on chicken/egg debate. Anywho, the GameStuff tells the event that when it is invoked, it should call the function ActOnRespawn, which as we can see, has the necessary parameters in the function definition.

    So, when the player dies, we'll assume PlayerDied gets called to respawn the player. Within this, it checks to see if anyone cares about the event (not a necessary check, but a good safety) and will invoke the event if necessary. You can think of this as calling a function, as that is pretty much what it is, it just doesn't know if/where these functions are in memory until they are hooked up at runtime.



    In your case, you could simply define the event as an EventHandler, which takes no arguments (and means no need for declaring the delegate) so Player.cs would be:


    Code:  
    1. namespace GenericEvents
    2. {  
    3.    class EventTriggerer
    4.    {
    5.        public event EventHandler OurEvent;
    6.  
    7.        public void TriggerEvent()
    8.        {
    9.           if(OurEvent != null)
    10.           {
    11.              OurEvent();
    12.           }
    13.        }
    14.    }
    15.  
    16.    class OtherObject
    17.    {
    18.          private EventTriggerer m_trig;
    19.          public SomeFunction()
    20.          {
    21.               if(GUI.Button)
    22.               {
    23.                    m_trig.TriggerEvent();
    24.               }
    25.          }
    26.    }
    27. }


    Every object that was going to trigger the event would need a handle to the object that contained the event to be triggered, but it would enable that event to be triggered by any other given object at any time and so anything that was in turn subscribed to the event OurEvent would be invoked accordingly.

    Hopefully that makes sense. It's late and when you use something every day, it sometimes becomes difficult to explain clearly without going into too much, unnecessary detail.


  6. Posts
    8

    update

    I've come here to find out about defining my events in c#, a matter in which I was completely ignorant until last week. This thread was immensely useful, thanks to everyone.

    Digging deeper i also found Advanced CSharp Messenger: http://wiki.unity3d.com/index.php?ti...harp_Messenger
    An updated version of the messenger linked in the above posts.

    Also, here is the link to a discussion where the messenger has been recently updated:
    http://forum.unity3d.com/threads/112...essenger/page2

    Hope it benefits anyone
    Last edited by paskal007r; 02-06-2014 at 04:13 AM. Reason: news

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •