I have a script that fires an event when a gameobject with the interface IInteractable enters a trigger collider. The script works great, but I want it to add any qualifying gameobject that enters the trigger to a list, and take them off the list when they exit the collider, and keep track of which of these objects is closest and fire the event for that one and ignore any others.
The problem is, the way I have it coded, it is looking for instances of IInteractable, and not gameobjects, so when trying to determine which is closest, I’m not able to access transform.position.
How do I cast the entering collider as a gameobject that has IInteractable attached?
Here is the code I have:
public bool interactableDetected = false;
public static event Action<IInteractable> CanInteract;
public static event Action<IInteractable> CannotInteract;
private void OnTriggerEnter(Collider other)
{
IInteractable interactable = other.GetComponent<IInteractable>();
if (interactable != null)
{
if(!interactableDetected)
{
CanInteract?.Invoke(interactable);
Debug.Log("Player is in range of " + other.name);
}
interactableDetected = true;
}
}
private void OnTriggerExit(Collider other)
{
IInteractable interactable = other.GetComponent<IInteractable>();
if (interactable != null)
{
if(interactableDetected)
{
CannotInteract?.Invoke(interactable);
Debug.Log("Player has left range of " + other.name);
}
interactableDetected = false;
}
}
This post is 4 years old many things has been deprecated.Post your question if you have problem in video calling unity.
– SohailBukhari