Question for line of code

Not sure if i can ask this here but i have a very specific thing im trying to do and im having trouble figuring out how to code it. I’m basically trying to make it to where theres a wall or secret door and when i press a button i.e space, the collider on said door will allow the player to pass through and if button is not pressed you cannot pass through, ive looked on forums trying to find how to do this but all lines of code ive tried have not worked.

The simplest way to do what you’re asking would be to put a script on the wall/door and disable the collider when the key you want to use is pressed. Assuming you’re using the old input system:

using UnityEngine;

public class SecretDoor : MonoBehaviour
{
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            GetComponent<Collider>().enabled = false;
        }
    }
}

One problem with this is it will work no matter where the player is, to fix that you’d need to get a reference to your player and check that the distance between them and this object are close enough for your liking.

There are much better (more complicated) methods such as using interfaces which could also be used more generically than just on (secret) doors.

1 Like

Or
Make a physics layer called something like “revealed” (or whatever you want). Put the door on another layer. Set the physics of the player to collide with this other layer, but not “revealed”. When you hold the button, set the door’s layer to “revealed”. When you let go, set it back to the original

Like @Satinel said, this will work no matter where the player is. You could put a trigger around the area and check in the OnTriggerStay if the button is pressed and only then set the layer/disable the collider. Disabling the collider will allow anything to pass through there, but with the layers you can make it so only the player can pass through but nothing else

1 Like

Privacy & Terms