Home>

If i know how to limit the functions that can be called from the Animation event, please let me know.
For example

public class Sample: Monobehaviour
{
  private void InitFromAnimation () {}
  private void InitFromScript () {}
}


I want to be able to execute only "InitFormAnimation", not "InitFromScript" from the animation of the object to which the script is attached.

In Animation event, only the function set in the animation clip is executed, but (if my recognition is correct) I think that all the functions in the Sample class may be called depending on the setting of Animation event.
However, considering safety and maintainability, we would like to limit the functions that can be called in Animation event.

In such a case, is there no choice but to limit the argument of "InitFromScript" by making it a class that cannot be serialized (?)?

The version of Unity is 2018.4.23f1.

  • Answer # 1

    Isn't there an attribute that prohibits execution from AnimationEvent?
    You may have to use non-intuitive means, as the questioner said. It's a little clunky,

    private void InitFromScript (bool dummyArg0 = false, bool dummyArg1 = false)
    {
        Debug.Log ("Do something");
    }

    Add a dummy argument likeInitFromScriptHow about having more than one argument for?
    AnimationEventThere seems to be a limitation that the method invocation by by must have 0 or 1 arguments, so this isAnimationEventIf you try to run from, it should fail.
    In addition, it seems that execution via SendMessage is also limited to one argument, so there will be an adverse effect of blocking that as well. Also, adding seemingly meaningless arguments may not be easy from a maintainability standpoint, even if it is for security reasons ...

    As an alternative, the investigation is insufficient,AnimationEventIt feels like there is no caller to execute the method from ...

    using System.Diagnostics;
    using UnityEngine;
    using Debug = UnityEngine.Debug;
    public class Sample: MonoBehaviour
    {
        private void InitFromScript ()
        {
            var previousFrame = new StackFrame (1);
            var caller = previousFrame.GetMethod ();
            if (caller == null)
            {
                Debug.Log ("Invoked from Animation Event?");
                return;
            }
            if (caller.Name == "SendMessage")
            {
                Debug.Log ("Invoked by SendMessage?");
                return;
            }
            Debug.Log ("Do something");
        }
    }

    Check the previous stack frame like thisAnimationEventIs it executed by?SendMessageYou may be able to identify whether it is done by or not.
    However, this may not work in the built release version without the debug symbol (unconfirmed). You may need to have a conditional compilation so that it only takes effect when in play mode.

Related articles