Clarification question

I find I have more success using a delegate/event set up, rather than using an Action, but I had a question about my coding, and Invoking said event…
For example, for the shop changing event, this is how I have set up my initial event…

       public delegate void ActiveShopChanged();
       public event ActiveShopChanged shopChanged;
       public void SetActiveShop(Shop shop)
        {
            activeShop = shop;
            if(shopChanged != null)
            {
               shopChanged?.Invoke();
            }

        }

my question is, do I need the null check, since I am using the “?” in my invoke… is that a redundant check? would the check for null be the same is I just wrote

       public delegate void ActiveShopChanged();
       public event ActiveShopChanged shopChanged;
       public void SetActiveShop(Shop shop)
        {
            activeShop = shop;           
            shopChanged?.Invoke();            

        }

This is not exactly related to the course, but I just want to make sure I am getting a grasp on the language. Thanks.

That is correct. If you are using null propogation on an event, delegate, System.Action, or UnityEvent, you do not need to null check, since the ? is the bit of syntactic sugar that does the null checking for you.

I’m not entirely sure why you wouldn’t have success using an Action in this case instead of declaring an ActiveShopChanged() delegate. Action is itself, a delegate. For example, in the case you have here:

public event Action shopChanged;

will work exactly the same as

public delegate void ActiveShopChanged();
public event ActiveShopChanged shopChanged;

The important thing about the delegate is determining the signature of the methods that can be attached to the event… Action by itself is a method with no parameters, and specifying a method with parameters is as simple as Action<float> (or whatever parameter types you wish).

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms