Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question What can replace public actions?

Discussion in 'Scripting' started by NeNpc, Nov 17, 2022.

  1. NeNpc

    NeNpc

    Joined:
    Aug 2, 2018
    Posts:
    3
    Hey everyone!

    I have organized interaction between interfaces through public Action. But they periodically tell me that this is a bad practice, but they don’t tell me how to do it better. I understand that such an architecture may have a problem with the fact that this Action can call an extraneous class (although in my opinion it is obvious that this is not necessary).
    Then I began to write such a construction, in the method and in the interface I indicated these methods.

    Code (CSharp):
    1.  
    2. private Action restartGameAction;
    3. public void RestartGameActionSubscribe(Action function) =>restartGameAction += function;
    4. public void RestartGameActionUnsubscribe(Action function) => restartGameAction -= function;
    5.  
    It seems to me that such a construction is redundant, but I did not come up with another method for solving the problem and did not google it.
    Please tell me what other methods are there to solve this problem?
     
  2. tomfulghum

    tomfulghum

    Joined:
    May 8, 2017
    Posts:
    69
    If you want to prevent other classes from invoking a delegate (like an Action), you can use the
    event
    keyword:
    public event Action RestartGameAction;
    . This way the RestartGameAction Action can only be invoked from the class containing it.
     
  3. NeNpc

    NeNpc

    Joined:
    Aug 2, 2018
    Posts:
    3
    Thank you so much! Exactly what I need.