- Home /
How to run a update function once
I have this code
public float speed;
// Start is called before the first frame update
void update()
{
if (Score.score > 2)
{
speed = 4;
KillPipes();
}
if(Score.score > 50)
{
speed = 5;
}
if(Score.score > 100)
{
speed = 6;
}
}
I only need this to run once, and then delete or disable the code, how can I do that?
Your code does not have an update function in it. The start function is only called once when the game runs. Isn't that what you want? To disable the code, just use that statement:
enabled = false;
i was ment to be in a void update, I copied the wrong thing, but now it is fixed, does enabled = false, still is a code that could stop this?
Yes, it will disable the script and the update function will not be called unless you enable it again by another script.
Answer by highpockets · Apr 29, 2020 at 07:01 AM
If you put the update function in a script and that script does not get destroyed after the first time it runs, it will continue. I think you are potentially looking for behaviour that can be provided by a coroutine:
void Start(){
StartCoroutine(OneUpdate());
}
IEnumerator OneUpdate(){
yield return new WaitForEndFrame();
//Your logic
}
Answer by FZ_Applications · Apr 29, 2020 at 07:35 AM
It is not clear what the question asks for.
The Start() method runs only once anyway.
If you want to destroy the script after execution you can write:
void Start(){
//Start Code
Destroy(this); //Destroys this script
}
If you want to destroy the gamObject after execution write:
void Start() {
//Start Code
Destroy(gameObject);
}
i copied the wrong script, but now i changed it, it is supposed to say void update not void start. and I would like for it to not run after, because now when the score reaches 2, it destroys the pipes non stop, and I would like for it to destroy them once and never run again.
Answer by MusapKahraman · Apr 29, 2020 at 11:08 PM
You can use enabled = false but it will disable the script and the update function will not be called unless you enable it again by another script.
private void Update()
{
if (score > 2)
{
speed = 4;
KillPipes();
enabled = false;
}
// This code will not reach beyond this line
if (score > 50)
{
speed = 5;
}
if (score > 100)
{
speed = 6;
}
}
Your answer
Follow this Question
Related Questions
Call A Function At A Certain Time 1 Answer
Update Just Once 3 Answers
Play sound ONCE! 3 Answers
Run function once, is this method appropriate? 2 Answers
Calling a method once in update 1 Answer