Skip to content

Instantly share code, notes, and snippets.

@samsheffield
Created September 27, 2021 00:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samsheffield/e0116c8217d87290c36bd98d4b9e2d2a to your computer and use it in GitHub Desktop.
Save samsheffield/e0116c8217d87290c36bd98d4b9e2d2a to your computer and use it in GitHub Desktop.
How to do something just once in Update
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JustOnce : MonoBehaviour
{
// Has the thing already been done?
private bool alreadyDone = false;
// Update is called once per frame
void Update()
{
// Signal that it's time to do something only once. In this example, press Space
if (Input.GetKeyDown(KeyCode.Space) == true)
{
// Only run the code in this if alreadyDone is false
if(alreadyDone == false)
{
// Do this thing only once and then...
Debug.Log("Just Once");
// Set this true to keeps the enclosing if() statement from being able to run again
alreadyDone = true;
}
}
}
}
Here is a bonus Unity example for 2D Game Design F21. Let me know what else you need!
======================================================================================
DO SOMETHING JUST ONCE IN A LOOP LIKE UPDATE
Full example: JustOnce.cs
Important:
1. A bool is used to create a condition that can't be re-entered once run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment