Search Unity

Question Finding Objects / Parameter use with Event Listeners

Discussion in 'Scripting' started by Ballaum, Jul 1, 2020.

  1. Ballaum

    Ballaum

    Joined:
    Dec 18, 2013
    Posts:
    3
    I've been starting to learn about using Events in my code, but have been running into a Problem using them where I seem to be missing a small difference between two cases:

    First Method (Working fine)

    Code (CSharp):
    1.  
    2. // Test Script
    3.     UnityEvent TestEvent = new UnityEvent();
    4.  
    5.     private void Awake()
    6.     {      
    7.         TestEvent.AddListener(GameObject.Find("TestObject").GetComponent<UIObject>().Toggle);
    8.     }
    Just finding the Object in Scene, getting the Script-Component from it, and adding the (in this case) Toggle Method as the Listener for the Test Event works perfectly fine.


    Second Method (Not working)

    Code (CSharp):
    1.  
    2. // Test Script
    3.     UnityEvent TestEvent = new UnityEvent();
    4.  
    5.     public void AddCustomListener(UIObject _object)
    6.     {
    7.         TestEvent.AddListener(_object.Toggle);
    8.     }
    9.  
    10. // UIObject Script
    11.     public void Start()
    12.     {
    13.         Test.Instance().AddCustomListener(this);
    14.     }
    I'd prefer to have the UIObjects to call the Manager Class (Test Class in this case) themselves instead of having the Manager look for everything themselves. So calling the AddCustomListener Method on the Test Script and having the UIObject be the Parameter, would be much easier (and flexible)
    However when I use the UIObject in the AddCustomListener Method, actually adding the Listener on the TestEvent doesn't seem to work.

    Can anyone explain to me the difference between those two cases?


    EDIT: In case someone is wondering, I found the answer. Using "Instance()" to make the Test Class a Singleton messed things up. Getting a direct reference to the Script from the Scene makes it work. Just a mistake when mixing two approaches that made me confused.
     
    Last edited: Jul 2, 2020
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    What's "DefaultEvent"? It's not a builtin Unity class and you don't explain what it is here.
     
    PraetorBlue likes this.
  3. Ballaum

    Ballaum

    Joined:
    Dec 18, 2013
    Posts:
    3
    I'm sorry it's just an Override of a Unity Event, nothing really different about it. Changed in Post