- Home /
Simple "do once" in Update issue.
I want the "print" message to display once. The problem is that it's in the Update function so it prints to infinity as long as it's true.
using UnityEngine;
using System.Collections;
public class Quest1Door : MonoBehaviour {
void Update()
{
if (Quest1.openedDoor) {
print("The door is now open.");
}
}
}
I tried putting break/return after it, but it's not a loop?
I also did a doOnce variable that was set to true, but it seems like a lot of extra code for something so simple. Then again, this is how Fallout 3/Oblivion scripts are done.
Answer by Eric5h5 · May 31, 2011 at 09:59 PM
Don't use Update, which always runs every frame regardless, and is very poor for any kind of event scheduling. Just call the function when you need to.
public class Quest : MonoBehaviour {
void PrintMessage (string message)
{
print message;
}
}
Get a reference to the Quest script, and when the player opens the door, do
questScript.PrintMessage ("The door is now open.");
I've changed it all into functions now. It's a little less easy to read because I have to get the object with GameObject.Find etc, but I guess it's the best way.
@Stardog: It should be easier to read if the code is structured properly. Also you might want to look into singletons: http://www.unifycommunity.com/wiki/index.php?title=A$$anonymous$$anagerClass
Answer by ronronmx · May 31, 2011 at 09:50 PM
You need to use a boolean flag that you turn on and off when needed:
using UnityEngine;
using System.Collections;
public class Quest1Door : MonoBehaviour {
private bool printDone;
void Start()
{
printDone = false;
}
void Update()
{
if (Quest1.openedDoor && !printDone) {
print("The door is now open.");
printDone = true;
}
}
}
By setting "printDone" to true in the IF statement, your print() text won't be displayed again until "printDone" is set back to false (for example, the next time you restart the scene).
Hope this helps, I couldn't test the code but it should work. Stephan
Answer by Stardog · Jun 21, 2011 at 01:02 PM
Another answer for this - use this Messenger script:
http://www.levelbylevel.com/tutorials/unity-c-messenger-tutorial
http://www.unifycommunity.com/wiki/index.php?title=CSharpMessenger_Extended
Make the door send send a message:
Messenger.Broadcast("door_opened");
Then, in the QuestScript, listen for it and change the variable with a function.
void OnEnable() {
Messenger.AddListener("door_opened", FunctionThatChangesVariable);
}
void OnDisable() {
Messenger.RemoveListener("door_opened", FunctionThatChangesVariable);
}
public void FunctionThatChangesVariable() {
print("The door is now open.");
}
Your answer
Follow this Question
Related Questions
OnTriggerEnter only recognised once, no matter how many times I enter ? (Solved) 1 Answer
Start, Awake, Update. Any other ways to call functions from an empty GameObject? 3 Answers
Print statement to execute multiple times 2 Answers
Finding Closest Enemy... 2 Answers
How to print user's guide 3 Answers