Created
September 27, 2021 00:40
-
-
Save samsheffield/e0116c8217d87290c36bd98d4b9e2d2a to your computer and use it in GitHub Desktop.
How to do something just once in Update
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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