I am trying to pick up a key by pressing “E” but as of now it can be picked up from anywhere. I tried implementing raycast, but I can’t get my code to work, it still picks up from anywhere and I keep getting errors. Can someone tell me what I am doing wrong? I have the script attached to the key.
public class KeyPickup : MonoBehaviour {
public bool inTrigger;
public bool camHover = false;
void OnTriggerEnter(Collider other)
{
inTrigger = true;
}
void OnTriggerExit(Collider other)
{
inTrigger = false;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update() {
Vector3 fwd = transform.TransformDirection (Vector3.forward);
var rayLength = 2;
var hit = RaycastHit;
if (Physics.Raycast (transform.position, fwd, hit, rayLength)) {
if (inTrigger)
{
camHover = true;
if (Input.GetKeyDown(KeyCode.E))
{
DoorScript.doorKey = true;
Destroy(this.gameObject);
}
}
}
}
void OnGUI()
{
if (inTrigger && camHover == true)
{
GUI.Box(new Rect(0, 60, 200, 25), "Press E to pick me up!");
}
}
}
Your OnTriggerEnter and OnTriggerExit callbacks don’t control the Collider. Tag your Player as “Player” and do this modification :
void OnTriggerEnter(Collider other)
{
if(other.CompareTag("Player"))
{
inTrigger = true;
}
}
void OnTriggerExit(Collider other)
{
if(other.CompareTag("Player"))
{
inTrigger = false;
}
}
This way you control if the object being entered in Key trigger is player.
Right now, your trigger can be enabled by anything.
Maybe you should write if(other.tag == “Player”){ isTrigger = true } and same goes for OnTriggerExit.
1)if you want to pick up the key by pressing E then use this code and attach this code to your key and attach collider and tick mark the isTrigger and remember if the key size is small then make its collider size a little large . and if you want to pick the key automatically when move near it then remove if(Input.GetKey(KeyCode.E)){ with remaining- closing bracket }
2)Assign your Player a tag of Player with capital P
public class PickupTheKey : MonoBehaviour
{
bool keyEquipped ;
// Use this for initialization
void Start()
{
keypickup.SetActive(false);
keyEquipped = false;
}
// Update is called once per frame
void Update()
{
}
public void OnTriggerEnter(Collider col)
{
if(Input.GetKey(KeyCode.E)){
if (col.gameObject.tag == "Player")
{
keypickup.SetActive(true);
keyEquipped = true;
Destroy(gameObject);
}
}
}
}