Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by overki11 · Jan 17, 2016 at 01:38 AM · nullreferenceexceptioneventeventsdelegate

Event NullReferenceException

Not working, don't know why. I've subscribed and everything, getting it on the TriggerEventTest script on line ten.

GamemanagerEvent:

 using UnityEngine;
 using System.Collections;
 
 public class GamemanagerEvent : MonoBehaviour {
     public delegate void GameEventHandler();
     public event GameEventHandler MyGameEvent;
 
 
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
     
     }
 
    public void OnMyGameEvent()
     {
         if (MyGameEvent != null)
         {
             MyGameEvent();
         }
     }
 }
 

TriggerEventTest: using UnityEngine; using System.Collections;

 public class TriggerEventTest : MonoBehaviour {
     GamemanagerEvent EventTest1;
     // Use this for initialization
 
     void Start () {
         EventTest1 = GameObject.Find("GameManager").GetComponent<GamemanagerEvent>();
         EventTest1.MyGameEvent += Print;
 
     }
 
     void Print()
     {
         Debug.Log("Test");
     }
 
     // Update is called once per frame
     void Update () {
     
     }
 
     void Teleport(GameObject thisGameObject) {
         thisGameObject.transform.position = new Vector3(0, 0, 0);
     }
 
     void OnTriggerEnter(Collider other)
     {
 
         EventTest1.OnMyGameEvent();
 
     }
 }



Also, is there a reason I should use events? I see no reason at all why I should use them. They are extremely confusing and I could just call a function instead.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by cjdev · Jan 17, 2016 at 04:22 AM

Imagine events as signal flares you fire up when you want something to happen. Which scripts that have prepared for it, or added a handler as it's often named, will then call the method they prepped. The reason this is so powerful is because it "de-couples" objects from each other and lets them be more independent. Imagine having 20 objects all calling methods in each other. Then you change a method and suddenly you might have to hunt down and find where you need to change the call in all those other objects. With events, the objects don't have to be aware of each other at all, they just say "hey, I want this done when that happens" or " hey, this is happening right now" and yet they still all communicate to one another... with the help of a third party. The event manager is what turns the analogy into code and is basically like a switchboard that handles relaying communication between objects. All it does it take commands to add and remove handlers, and commands to broadcast the events. This is what it might look like in code:

 using System.Collections.Generic;
 using System;
 
 public enum EVENT { Event1, Event2 }; //... Add your events here
 public static class EventManager {
 
     // An Action is a delegate, this contains the Actions for each event
     private static Dictionary<EVENT, Action> eventTable
              = new Dictionary<EVENT, Action>();
 
     // Adds an action to be called when the specified event is broadcast
     public static void AddHandler(EVENT e, Action action)
     {
         if (!eventTable.ContainsKey(e)) eventTable[e] = action;
         else eventTable[e] = eventTable[e] + action; // You can add delegates
     }
 
     // Calls the action that contains all the registered handlers
     public static void Broadcast(EVENT e)
     {
         Action action;
         if (eventTable.TryGetValue(e, out action)) // Make sure theres an action
             if (action != null) action();     // that isn't empty before calling
     }
 
     // Removes an action from the event action and removes that if it's empty
     public static void RemoveHandler(EVENT e, Action action)
     {
         if (eventTable[e] != null)                  
             eventTable[e] = eventTable[e] - action; // Subtracting works as well
         if (eventTable[e] == null)                  // If there isn't an action
             eventTable.Remove(e);                   // then remove the event key
     }
 }

And how it would be used:

 using UnityEngine;
 using System;
 
 public class A: MonoBehaviour {
 
     void Awake()
     {
         Action foo = Foo;
         EventManager.AddHandler(EVENT.Event1, foo);
     }
 
     private void Foo()
     {
         Debug.Log("Foo");
     }
 
 }

 /////////

 using UnityEngine;
 
 public class B: MonoBehaviour {
 
     void Start()
     {
         EventManager.Broadcast(EVENT.Event1);
     }
 }
 
 // Output is "Foo"


You can see that class B is basically able to run a method in class A without ever actually linking itself to A at all. This way, if you were to edit class A, or remove it entirely and replace it with something else, you would be just fine in class B because all it does is fire the event. I should probably mention that I replaced the delegate from your code with Action because it's basically a modern shortcut that gets rid of having to define the delegate first. At any rate, hope that clears things up a bit.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Madblackster · Oct 15, 2017 at 10:54 AM 0
Share

you saved my life and, on top of that, display a really good way to build an event manager. Thanks a lot!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

39 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Question regarding delegates and events 1 Answer

Instance variables and this == null in event handler 1 Answer

UnityEvent NullreferenceException in inspector 0 Answers

NullReferenceException was thrown when raise an event 0 Answers

UnityEvent is not showing Dynamic or Static Parameters Label in the inspetor,In my Custom Unity Event Dynamic or Static Parameters Not Appearing 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges