I am trying to display a message saying 'Press E to talk to NPC' when the player is collided with the NPC collider and when the player is not collided with the NPC the message is disabled. The message does appear upon collision but it does not disabled when there are no collisions I have tried so many things but nothing seem to work. Can anyone help? HERE IS MY CODE AND SOME THINGS I HAVE TRIED:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Task_7 : MonoBehaviour
{
public GameObject PressEmsg;
//public bool isNearNPC = true;
// Start is called before the first frame update
void Start()
{
PressEmsg.gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
Collider[] nearbyColliders = Physics.OverlapSphere(transform.position, 5f);
//bool isNearNPC = false;
//we are looping in the array hitColliders
foreach(Collider collider in nearbyColliders)
{
if(collider.gameObject.tag == "NPC")
{
PressEmsg.gameObject.SetActive(true);
print("NPC DETECTED");
//isNearNPC = true;
}
else
{
PressEmsg.gameObject.SetActive(false);
print("NPC NOT DETECTED");
}
/*
else if(collider.gameObject.tag != "NPC")
{
PressEmsg.gameObject.SetActive(false);
print("NPC NOT DETECTED");
}
*/
}
/*foreach(Collider collider1 in notnearbyColliders)
{
if(collider1.gameObject.tag != "NPC")
{
PressEmsg.gameObject.SetActive(false);
print("NPC NOT DETECTED");
}
}
*/
}
}