- Home /
Code executes more than once when key press event is triggered in OnGui in Custom Editor Window
So I have a custom editor window script and I am trying to tell if a button combination is pressed in ongui and have it execute an action once.
private void OnGUI(){
if (Event.current.type == EventType.MouseDrag && Event.current.button == 0)
{
if( Event.current.alt){
//do stuff
Event.current.Use();
}
}
}
Now the problem is the stuff that pressing this button combination does happens a lot more than once when I only want it to happen once until the user releases the alt button and presses it again. I have also tried
private bool CanDoStuffAgain = true;
private void Update(){
if(!Input.GetKey(KeyCode.Alt) && CanDoStuffAgain == false){
Debug.Log("Can do stuff again");
CanDoStuffAgain = true;
}
}
private void OnGUI(){
if ((Event.current.type == EventType.MouseDrag && Event.current.button == 0) )
{
if(Event.current.alt && CanDoStuffAgain == true){
//do stuff
CanDoStuffAgain = false;
Event.current.Use();
}
}
Now when I do this the debug message just keeps printing over and over even when I have Alt pressed. This means for whatever reason Input.GetKey isn't working properly in Update. I also have a [ExecuteInEditMode] attribute above my class, but am not sure if it is needed or if Update runs regardless. Anyways I basically just want my stuff that happens when alt is pressed while the user is dragging to happen once and not happen again unless the user stops pressing alt and then presses it again. Is there any way to accomplish this?
Answer by Raimi · Jun 12, 2017 at 11:43 PM
You could use a coroutine maybe?
void Start()
{
StartCoroutine(fire());
}
IEnumerator fire()
{
// Do something
yield break;
}
Answer by JonPQ · Jun 13, 2017 at 12:35 AM
OnGui updates more than once per frame.... its very annoying instead set some flags from your button scripts, and put your checking code elsewhere, in a regular script on a gameobject that updates once a frame.
Well the problem with putting this code in a regular script on a gameobject is that this code is part of a custom editor window that is part of a tool, something that will never be in the scene anywhere. I also tried checking in Update with Input.Get$$anonymous$$eyDown and Input.Get$$anonymous$$ey. It never returns true for some reason, even when alt is pressed down.
How about checking system time.... Time.currentTimeSinceStartup when your button is pressed, call your function... and store time in a variable at the end of function. at start of function... if the time elapsed is too small.... ignore the button click and exit.
Answer by Jeremy-Borton · Apr 05, 2018 at 12:09 PM
I need help on this too. I got the same problem...
Your answer
Follow this Question
Related Questions
OnGui elements as objects? 2 Answers
Distribute terrain in zones 3 Answers
How do I create custom editor window layout through script ? 0 Answers
Undo.RecordObject and Constructor of Serializable Class 0 Answers