// Interactable.cs - Base abstract class for all interactable objects
|
using UnityEngine;
|
using UnityEngine.Events;
|
|
public abstract class Interactable : MonoBehaviour
|
{
|
[SerializeField] private string promptMessage = "Press E to interact";
|
[SerializeField] private float interactionDistance = 3f;
|
|
// Event that will be triggered when the player interacts with this object
|
public UnityEvent OnInteract = new UnityEvent();
|
|
// Each derived class must implement how it processes interaction
|
public abstract void Interact();
|
|
// Returns the prompt message for UI display
|
public string GetPromptMessage()
|
{
|
return promptMessage;
|
}
|
|
// Check if player is within interaction distance
|
public bool IsInRange(Transform playerTransform)
|
{
|
float distance = Vector3.Distance(transform.position, playerTransform.position);
|
return distance <= interactionDistance;
|
}
|
|
// Optional: Visualize interaction range in editor
|
private void OnDrawGizmosSelected()
|
{
|
Gizmos.color = Color.yellow;
|
Gizmos.DrawWireSphere(transform.position, interactionDistance);
|
}
|
private void OnTriggerEnter2D(Collider2D other)
|
{
|
if (other.gameObject.layer == LayerMask.NameToLayer("Player"))
|
{
|
// Player entered trigger zone
|
PlayerInteraction playerInteraction = other.GetComponent<PlayerInteraction>();
|
if (playerInteraction != null)
|
{
|
playerInteraction.SetCurrentInteractable(this);
|
}
|
}
|
}
|
|
protected void OnTriggerExit2D(Collider2D other)
|
{
|
if (other.gameObject.layer == LayerMask.NameToLayer("Player"))
|
{
|
// Player exited trigger zone
|
PlayerInteraction playerInteraction = other.GetComponent<PlayerInteraction>();
|
if (playerInteraction != null)
|
{
|
playerInteraction.SetCurrentInteractable(null);
|
}
|
}
|
}
|
}
|