Search code examples
unity-game-engineuser-interfaceanimationcanvasraycasting

Property "Raycast target" does not work in animation


TL;DR - Property "Raycast target" (from Image in Canvas) is successfully animated but has no real effect (passes events through itself when it should not).


I have Image in Canvas that I am animating. In animation I change "Raycast target" property so I can interact with buttons behind after the animation ends.

Propery changes in inspector, but has no effect - I can press buttons behind when animation hasn't finished yet and "Raycast target" is "True".

When I do not use animation and change propery directly through script - everything works as expected.

What am I missing?

My Scene:

Canvas
     |-Buttons
     |-Image (Foreground, Animated)

My animated Image:

enter image description here

My Animation:

enter image description here

Note: "Write Defaults" in animator does not affect anything.

Unity 2020.3.8.f1 LTS


Solution

  • I have not found solution, so I fixed problem through script. It checks animator state and manually changes property. In my case I have "Idle" state that is active when animation is not playing.

    public class RaycastTargetFix : StateMachineBehaviour
    {
        public string interactableState = "Idle";
    
        public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
        {
            var image = animator.GetComponent<Image>();
            if (image) image.raycastTarget = !stateInfo.IsName(interactableState);
        }
    }
    

    Script needs to be added to animator:

    enter image description here

    Of course raycastTarget property should not be animated, otherwise it cannot be changed through script.