- Home /
Only once in update
Hello guys. Is any way to make something only once in update without bools? I have to do a few things once in update but making bool for every is really impractical. Thank you in advance for answer:)
Answer by andrew-lukasik · Jul 30, 2017 at 07:50 PM
Yes. It's "Start" - called just before Update, called only when enabled, called only once.
Second option Is "OnEnable" - called always before Update, called every time Behaviour is enabled (so it's like Start but called every time Behaviour is re-Started).
Third option (not for newbies tho), if you really (and I mean reeeeeeeeally) need to use that Update calls (I'm pretty sure you do not) - would be to create field of type System.Action. It will allow you to group arbitrary number of method calls under one field and, interestingly enough, remove/add methods from that group - runtime.
using UnityEngine;
public class Example : MonoBehaviour
{
System.Action _onUpdate;
bool something = true;
void Awake ()
{
//initialize _onUpdate with one job:
_onUpdate = new System.Action( JobA );
//add JobB if something is true:
if( something )
{
_onUpdate += JobB;
}
}
void Update ()
{
//execute all methods in this group:
_onUpdate();
//word of warning: trying to execute a non-initialzed System.Action field
//will throw NullException. You can fix this by initializing this field
//(in Awake, for example) or testing for null just before execution
}
void JobA ()
{
Debug.Log("Tinky-Winky");
}
void JobB ()
{
Debug.LogWarning("Laa-Laa");
//removes self when executed once:
_onUpdate -= JobB;
}
void JobC ()
{
Debug.LogError("Po");
}
public void AddJobC ()
{
_onUpdate += JobC;
}
public void RemoveJobC ()
{
_onUpdate -= JobC;
}
public void AddVeryDifferentJob ( System.Action job )
{
_onUpdate += job;
}
}
wow!! thank you so much! I wouldn't ask unless I really needed help:)
Cool. Just make sure not to confuse "+=" and "-=" operators with "=",one missing sign - big difference and easy to miss.
Your answer
Follow this Question
Related Questions
Change Bool When Audio Clip Ends C# 1 Answer
Call A Function At A Certain Time 1 Answer
Update Just Once 3 Answers
Boolean Trouble, Please help....Boolean does not flip another boolean 0 Answers
c# Ignoring conditional statement? 1 Answer