Event when key pressed and when trigger is activated

The goal is to have the player enter a triggerbox, then be allowed to press the “E” key to destroy an object and spawn a new one.

This is the code I have for when the player collides with the triggerbox

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

public class SwitchCubeScipt : MonoBehaviour
{
    public GameObject goodcube;
    public GameObject badcube;


    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.name == "Cylinder")
        {
            Debug.Log("collided");
            if (Input.GetKeyDown(KeyCode.E))
            {
                Debug.Log("key pressed");
                Destroy(badcube);
                Instantiate(goodcube, transform.position, Quaternion.identity);
            }


        }
    }
}

This code is a component on the triggerbox
Nothing shows up in the console so the, collison with the trigger isn’t working.

Here is the scene. “GoodCube” is a prefab the cylinder is the player and the black cube is “BadCube”

If it’s a trigger you need to use OnTriggerEnter/Exit: Unity - Scripting API: Collider.OnTriggerEnter(Collider)

Make sure you read the docs to ensure you’re satisfying all conditions for triggers to fire.

But pretty much you need to record when the player enters/exits the trigger, but still handle input via update (as input is a frame based thing).

For example:

public class TriggerInputExample : Monobehaviour
{
    private bool _canTrigger = false;
  
    private void Update()
    {
        if (_canTrigger && Input.GetKeyDown(KeyCode.E))
        {
            // do stuff
        }
    }
  
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Cylinder"))
        {
            _canTrigger = true;
        }
    }
  
    private void OnTriggerExit(Collider other)
    {
        if (other.gameObject.CompareTag("Cylinder"))
        {
            _canTrigger = false;
        }
    }
}
2 Likes

Alternatively:

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

public class SwitchCubeScript : MonoBehaviour
{

    public GameObject goodcube;
    public GameObject badcube;


    void OnTriggerStay(Collider other)
    {
        if (Input.GetKey(KeyCode.E) && badcube)
        {
            Debug.Log("key pressed");
            Destroy(badcube);
            Instantiate(goodcube, transform.position, Quaternion.identity);
        }
    }

}
1 Like

OnTriggerStay happens in the physics loop (eg, FixedUpdate), so I wouldn’t use it to handle input.

Yeah I wouldn’t use it with GetKeyDown but GetKey is fine.