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. Dismiss Notice

Question Events fired on a custom class object after unsubscribing

Discussion in 'Scripting' started by Leonid, Apr 24, 2022.

  1. Leonid

    Leonid

    Joined:
    Aug 20, 2013
    Posts:
    90
    I have a custom class for effects logic.
    An effect subscribes to an event when it is created.
    This works fine, but even after the effect has timed out and the OnEnd method has been called and the event reference is removed, the effect STILL receives the event and DoSomeStuff is still called.
    How can I solve it?
    Thank you!

    Code (CSharp):
    1.  
    2. public class Effect
    3. {
    4.    public float timer = 10f;
    5.  
    6.    public void OnStart()
    7.    {
    8.       EventsManager.SomeEvent +=DoSomeStuff;
    9.    }
    10.  
    11.    private void DoSomeStuff()
    12.    {
    13.    }
    14.  
    15.    public void OnEnd()
    16.    {
    17.       EventsManager.SomeEvent -=DoSomeStuff;
    18.    }
    19. }
    20.  
    21. public class SomeClass: MonoBehaviour
    22. {
    23.    private Effect effectTemp;
    24.    private List<Effect> effects = new List<Effect>();
    25.  
    26.    public void AddEffect()
    27.    {
    28.        effectTemp = new Effect();
    29.        effect.OnStart();
    30.        effects.Add(effect)
    31.    }
    32.  
    33.    private void Update()
    34.    {
    35.       for (int i = effects.Count - 1; i >= 0; i--)
    36.       {
    37.          effectTemp= actorEffects[i];
    38.  
    39.          effectTemp.time-=Time.deltaTime);
    40.  
    41.          if (effectTemp.time< 0.001f)
    42.          {
    43.             effectTemp.OnEnd();
    44.             effects.Remove(effectTemp);
    45.             effectTemp= null;
    46.          }
    47.       }
    48.    }
    49. }
     
    Last edited: Apr 24, 2022
  2. Leonid

    Leonid

    Joined:
    Aug 20, 2013
    Posts:
    90
    Well it turns out I was not checking if I already subscribed before subscription, so there were more subscriptions then unsubscriptions.
    Rookie mistake.
    Dear moderator, could you please delete this thread? It seems that I cant do it.
     
    Bunny83 likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,717
    This is by design. The idea is that this forum is an accumulating wealth of struggles and solutions.

    This means your second post is AWESOME, because you took the time to come back and say what it was. Your writing will likely help someone far in the future having a similar issue.
     
    Leonid and Bunny83 like this.