Search Unity

Switches in Update question

Discussion in 'Scripting' started by miha4406jp, Jun 10, 2021.

  1. miha4406jp

    miha4406jp

    Joined:
    Apr 8, 2021
    Posts:
    9
    Hello. I want to do something only once in Update(), and I'm using boolean switches to do so.
    My question is: is there any better/elegant way to do so? Like not adding ton of bool variables ad hoc.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Without knowing what you want to do, it's impossible to tell you. Update runs every frame no matter what. Unless, you turn the gameobject or script off. But, if you are trying to check for a bool to become true, then run code and set it back to false, then you have to have the bool. Or, at least you have to have a conditional check to determine when that single execution must happen.

    But again, without knowing what you want to do, it's impossible to offer real alternatives to your use case.
     
    lordofduct likes this.
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    Show us your code, we could better assess your situation that way. Otherwise anything we say is just conjecture.
     
    Bunny83 likes this.
  4. miha4406jp

    miha4406jp

    Joined:
    Apr 8, 2021
    Posts:
    9
    Thanks for reply. So, there is no universal alternative? That's is what I wanted to know.
     
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,500
    You want some standard way to only do something once in a callback that happens evey frame? Seems a little odd if I'm honest.

    Use a callback that only happens once such as Start.
     
    lordofduct likes this.
  6. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    if statements, switches, and branching in general are fundamental aspects of coding. If there was a universal replacement, they wouldn't be there.

    As for your specific use case... we don't know, since we don't know your specific use case. Show us, even show an example, and maybe then we can.

    But so far we only know "do something only once in update"... what does that even mean? If I wanted to do something only once, I wouldn't do it in Update, I would do it when it's called for (such as Start, Awake, OnCollisionEnter, whatever moment upon which the "once" is supposed to happen, etc).
     
    Brathnann and MelvMay like this.