Search Unity

Question Event triggered twice

Discussion in 'Unity Transport' started by Xa456789, Feb 12, 2024.

  1. Xa456789

    Xa456789

    Joined:
    Aug 5, 2022
    Posts:
    24
    When using a event with a non-monobehavior it gets triggered twice on invoke.
    Code (CSharp):
    1. public class ClassA
    2. {
    3.     public event EventHandler ontest;
    4.  
    5.     private static ClassA _instance;
    6.  
    7.     private static readonly object _lock = new object();
    8.     public static ClassA Instance
    9.     {
    10.         get
    11.         {
    12.             lock (_lock)
    13.             {
    14.                 if (_instance == null)
    15.                 {
    16.                     _instance = new ClassA();
    17.                 }
    18.                 return _instance;
    19.             }
    20.         }
    21.     }
    22.  
    23.     public void triggerTest()
    24.     {
    25.         ontest?.Invoke(this, EventArgs.Empty);
    26.     }
    27. }
    28.  
    29. public class ClassB : MonoBehaviour
    30. {
    31.     private void Awake()
    32.     {
    33.         ClassA.Instance.ontest += testEvent;
    34.         ClassA.Instance.triggerTest();
    35.     }  
    36.    
    37.     public void testEvent(object sender, EventArgs e)
    38.     {
    39.         Debug.Log("Test Event triggered!");
    40.     }
    41. }
    I'm using a OnPlayerConnected Event, wich adds dummies for every player except the new player. The server send a packet wich gets received by the new player, this client willl then send a nother packet to every client. When it gets received it will trigger this event: here I noticed that there are always two calls. I have traced it back, but it also happens with the example code above. Is there something about UnityTransport and Events or...?
     
  2. epiphj

    epiphj

    Joined:
    Apr 6, 2022
    Posts:
    1
    I noticed the same thing today. How have you handled this so far?

    EDIT: I found my reason. I had two instances of the subscribing script by mistake.
     
    Last edited: Feb 23, 2024