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

Function Timing

Discussion in 'Scripting' started by netside, Dec 12, 2014.

  1. netside

    netside

    Joined:
    Nov 3, 2014
    Posts:
    9
    I've been learning a little Unity scripting lately, and I have a little JS script that currently prints a simple debug.log() message to the screen every frame (because it's called inside the update function, which I know is called every frame). How could I make it so the function only logs a message to the console every few seconds? I tried using yeildwaitforseconds(), but it doesn't work because the update function is being called every frame.

    I figured I could just use some sort of counter, but it seems like the wrong way of doing it for some reason.

    Any help would be greatly appreciated... I'm stumped.
     
  2. damian.doroba

    damian.doroba

    Joined:
    Apr 4, 2013
    Posts:
    36
    You can use yield from method Start() but not from update
     
  3. netside

    netside

    Joined:
    Nov 3, 2014
    Posts:
    9
    Is there *any way* whatsoever to make something happen at certain intervals, just by scripting?
     
  4. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    If you mean in the update, since using a coroutine is scripting, then you would just keep track of time and print the debug when one second has elapsed. You could look at the time functions, but TimeSinceLevelLoad might work.
    Code (csharp):
    1.  
    2. float nextTime;
    3. void Start(){
    4. nextTime = Time.TimeSinceLevelLoad + 1.0f;
    5.  
    6. }
    7. void Update(){
    8. if(Time.TimeSinceLevelLoad > nextTime){
    9. Debug.Log("a message");
    10. nextTime = Time.TimeSinceLevelLoad + 1.0f;
    11. }
    12. }
    13.  
     
    Last edited: Dec 16, 2014
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    In general, don't use Update if you don't want something updated every frame. Aside from using yield in coroutines, a simple way of doing stuff at intervals is to use InvokeRepeating.

    --Eric