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.

How to Use System.Timers.Timer With unity GameObjects

Discussion in 'Scripting' started by ilyamep, Aug 6, 2022 at 12:07 PM.

  1. ilyamep

    ilyamep

    Joined:
    Feb 21, 2015
    Posts:
    12
    Hi

    Code (CSharp):
    1.  
    2. System.Timers.Timer timer = new(2000);
    3.         timer.Start();
    4.  
    5.         timer.Elapsed += delegate
    6.         {
    7.             Debug.Log("Tick");
    8.             Debug.Log(gameObject.Name);
    9.         }
    10. ;
    It does not write gameobject name in console window, is there any solution for this?
     
    Last edited: Aug 6, 2022 at 12:18 PM
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,111
    Just use coroutines? Or, if you're dead-set on using Timers, read the examples on the documentation to figure out how to implement them.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    26,948
    Find out how Timer works... does it call that delegate in another thread?

    If so, that will NEVER work with Unity. With Unity 100% of EVERYTHING you do must be on the main thread.

    Use coroutines.

    Coroutines in a nutshell:

    https://forum.unity.com/threads/des...en-restarting-the-scene.1044247/#post-6758470

    https://forum.unity.com/threads/proper-way-to-stop-coroutine.704210/#post-4707821

    Splitting up larger tasks in coroutines:

    https://forum.unity.com/threads/bes...ion-so-its-non-blocking.1108901/#post-7135529

    Coroutines are NOT always an appropriate solution: know when to use them!

    https://forum.unity.com/threads/things-to-check-before-starting-a-coroutine.1177055/#post-7538972

    https://forum.unity.com/threads/heartbeat-courutine-fx.1146062/#post-7358312

    Our very own Bunny83 has also provided a Coroutine Crash Course:

    https://answers.unity.com/questions...ected.html?childToView=1749714#answer-1749714
     
unityunity