Animation not playing when pressing E | unity 3d

Viewed 29

I am working on this 3d game were a player has to press E to interact with objects. the player has a collider that when touching a type of trigger that has this type of code, makes an object pop up showing that the player's is "selecting" something. when the player is in the trigger I made it were when they press E, the objects animation plays. When adding the objecting selecting thing it made it now that I cant make the animation play when pressing E

    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Fixedpress : MonoBehaviour
{
    public Animator Tributton;
    public GameObject GM;
    private Coroutine routine;

    private void Start()
    {
        GM.SetActive(false);        
    }



    private void OnTriggerStay(Collider other)
    {
        // in general rather use CompareTag instead of ==
        // it is slightly faster and also shows an error if the tag doesn't exist instead of failing silent
        if (!other.CompareTag("LookTrig")) {

            GM.SetActive(true);
            
            return; 
        
        }

        // just in case to prevent concurrent routines
        if (routine != null) StopCoroutine(routine);

        // start a new Coroutine
        routine = StartCoroutine(WaitForKeyPress());
    }

    private IEnumerator WaitForKeyPress()
    {
        // check each FRAME if the key goes down
        // This is way more reliable as OnTriggerStay which is called
        // in the physics loop and might skip some frames
        // This also prevents from holding E while entering the trigger, it needs to go newly down 
        yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.E));

        // set the trigger once and finish the routine
        // There is no way to trigger twice except exit the trigger and enter again now
        Tributton.SetTrigger("Fiveyon");
        Debug.Log("Fiveyon!");

        // If you even want to prevent this from getting triggered ever again simply add
        enabled = false;
        // Now this can only be triggered ONCE for the entire lifecycle of this component 
        // (except you enable it from the outside again of course)
    }

    void OnTriggerExit(Collider other)
    {
        if (!other.CompareTag("LookTrig")) {
            GM.SetActive(false);
            return; 
            
        }

        // when exiting the trigger stop the routine so later button press is not handled
        if (routine != null)
        {
            
            StopCoroutine(routine);
            GM.SetActive(false);
        }
    }
}
1 Answers

OnTrigger methods are called when another object with a Collider enters in your object Collider.
First, make sure everything was well set up well, and maybe you want to use OnCollision instead of OnTrigger methods, if you want to detect a collision whether than a "penetration" if i may say

Related