I’m trying to write a script to pick up a key, but it is not working.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Key : MonoBehaviour
{
public static bool HasKey = false;
private void Awake()
{
HasKey = false;
}
private void OnTriggerStay(Collider other)
{
if (other.tag=="Player")
{
if (Input.GetKeyDown(KeyCode.F))
{
HasKey = true;
Destroy(gameObject);
}
}
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
Put some Debug.Log statements in various places to see what code is and isn’t being run. Is OnTriggerStay being run? is the other.tag being true? if Input.GetKeyDown true? If you know at which point the chain is broken, you know what needs to be fixed.
Adding more to Ray’s suggestion, to help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.
Doing this should help you answer these types of questions:
is this code even running? which parts are running? how often does it run?
what are the values of the variables involved? Are they initialized?
Knowing this information will help you reason about the behavior you are seeing.