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 Multiple animation events call the same function on a singleton instance, what happens?

Discussion in 'Scripting' started by johannesQb, May 5, 2023.

  1. johannesQb

    johannesQb

    Joined:
    Jan 18, 2022
    Posts:
    10
    Hi, I have a question about concurrency, i cannot find answer anyware.
    Example: I have two instance of prefab, prefabA and prefabB, each of them has an animation with a event, and than i have a singleton class with a function F.
    I think it's almost impossbile, but what happens if prefabA and prefabB events are called at same time and each of them call function F? In the following example can i be sure that F is called two times, sequentially? Or can it happens a concurrency situation, for example while F is executed by prefabA, prefabB call F and value become 2 before the if and //do stuff not executed?

    Singleton class:
    Code (CSharp):
    1. int value = 0;
    2.  
    3. public void function F()
    4. {
    5.      value++;
    6.      if (value ==1)
    7.      {
    8.         // do stuff
    9.         value = 0;
    10.      }
    11. }
    Thanks
     
  2. Qriva

    Qriva

    Joined:
    Jun 30, 2019
    Posts:
    1,123
    Unity runs on single thread, it is not possible that some code will step in the middle of execution.
    Everything is sequential, unless you intentionally use the job system or something like that, but that cannot happen by mistake :D
     
    Bunny83 likes this.
  3. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    Because Unity runs on a single thread, in your thought example, events are resolved in some undefined order, sequentially. Most likely in reverse order from how the listeners were subscribed to the events, but system offers no guarantees for this.
     
    Bunny83 likes this.
  4. johannesQb

    johannesQb

    Joined:
    Jan 18, 2022
    Posts:
    10
    Perfect! Thanks to everyone