How to play animations on entering a trigger and pressing a button? (2D)

Hi guys! So, I’m working on a college assignment, and for it I have to have 10 interactable objects in a scene. What I was wondering is, how would I go about making it so that an animation plays when the player is inside a trigger and pressing a key? I have some code here that returns no errors but doesn’t seem to work either:

void Start()
{
    boardAnim = GetComponentInChildren<Animator>();
}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player" && Input.GetKeyDown("space"))
    {
        boardAnim.SetTrigger("isOpening");
        print("key pressed");
    }
}

(Had to cut the boardAnim initialization and a bracket at the end for formatting purposes)

Any help with this would be appreciated! :smiley:

OnTriggerEnter and OnTriggerExit fire on the same frame that the trigger event occurs, however, your input will most generally be processed on the next frame, so things just will never line up. So what you want to do is process the trigger event, set a boolean to true, and in your Update callback process the input if they’re standing in the trigger:

bool isInTrigger = false;

void Start()
{
    boardAnim = GetComponentInChildren<Animator>();
}

void Update()
{
    if (!m_isInTrigger)
        return;

    if (Input.GetKeyDown("space"))
        boardAnim.SetTrigger("isOpening");
}

void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player")
        m_isInTrigger = true;
 }

void OnTriggerExit2D(Collider2D other)
{
    if (other.tag == "Player")
        m_isInTrigger = false;
}