- Home /
Question by
InsertNamehere · Mar 15, 2015 at 07:00 PM ·
collidertriggerenter
OnTriggerEnter Get Key
Hey guys, i'm new to the Unity3D and i'm trying to do something. If player is in the Trigger he/she needs to press a button in keyboard in order to get in the house. I tried everything but i couldn't make it work. I'm making a 2D game with sprites.
Sorry for my bad English. Thanks!
Comment
Answer by asadi · Mar 16, 2015 at 06:36 AM
try using this code you need to have a tag "house" attached to the house
using UnityEngine;
using System.Collections;
public class enteringthehouse : MonoBehaviour {
bool enter; // boolean to determine whether you are inside the trigger or outside
void Start () {
enter = false; // before entering the trigger area
}
// Update is called once per frame
void Update () {
if (enter == true&& Input.GetKeyDown(KeyCode.Space)) // determine that only after the trigger is
{ // true and you press space you can enter the house
Debug.Log ("you can enter the house");//open the door ?/ change to other scene ? up to you
// just put the code here
}
}
void OnTriggerEnter (Collider collider)
{
if (collider.gameObject.CompareTag ("house")) //entering the trigger/collider attached to the
// house. the house object must have tag named "house"
{ // with both of these enter will only be true when you are
enter = true; // inside the trigger
}
}
void OnTriggerExit (Collider collider)
{
if (collider.gameObject.CompareTag ("house")) //exiting the trigger/collider attached to the
{ // house cause enter to become false
enter = false;
}
}
}
Very helpful answer. I used this to modify my random spawner in my game. When the player moves to an set area and right clicks the mouse, spawn a random block. When the player leaves the area the right click will no longer work. It looks like this.
screen-shot-2018-01-02-at-61546-pm.png
(100.2 kB)
Your answer
![](https://koobas.hobune.stream/wayback/20220613190131im_/https://answers.unity.com/themes/thub/images/avi.jpg)