Delegate events inside Update
Hi I usually come up with this "problem" and want to know if there's a better way to do it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Example: MonoBehaviour {
public delegate void ExampleEvents();
public static event ExampleEvents E_JustAnEvent;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (animator.GetCurrentAnimatorStateInfo(0).IsName(walkState))
{
if (E_JustAnEvent!= null)
E_JustAnEvent();
Debug.Log("event multiple times");
}
}
}
The problem is that of course the event gets triggered each frame, so I usually fix this by having a flag variable so it gets triggered only the first time.
It's ok when you have only one or even two events in the Update but the moment you have more, it becomes a hassle.
Also I usually don't like to use too much the Update function but sometimes is needed like in this case checking the animation state.
What do you suggest?
(I don't like though, using in Editor solutions for example adding an animation event set in the Editor)
Thanks!
Did you know you can add script to animation state?
Yes, but that's why I mentioned in my question that I don't want to use in editor solutions (only because it's more manageable in the company I'm working atm)
Your point brings up the more general wisdom that if an issue is fixed by a configuration of the editor, the problem is actually still left in the code and isn't, therefore, portable to usage elsewhere. It is not just the company your working in, but the act of working with others at all, or where code may ever be exported to other projects, or made a public product for other programmers. It is better to fix the code so the problem no longer exists, and never has to be fixed by configuration of the editor.
Also the question doesn't have to do with animation, but with ways to trigger events only once in the Update function
You can add event for animation clip at run time. That way, it will only call the event when animator run/go through it.
Get the animation clip inside your animator GameObject in awake. Then add an event(time 0.1f) for it.
nice idea about adding anim events at runtime
Your answer
![](https://koobas.hobune.stream/wayback/20220612171327im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Question regarding delegates and events 1 Answer
Different approach to an upgrade system 4 Answers
When should i be using events 1 Answer
Instance variables and this == null in event handler 1 Answer