Files
FablishRPG/Assets/Scripts/WorldObject.cs

89 lines
2.7 KiB
C#
Raw Normal View History

2026-09-28 20:46:57 +01:00
using UnityEngine;
using UnityEngine.Events;
public class WorldObject : MonoBehaviour
{
[Header("Data Template")]
[Tooltip("The Scriptable Object that defines what this item actually is.")]
public ObjectData data;
[Header("Instance State")]
[Tooltip("How many of this item are in this stack? (e.g. 5 arrows)")]
public int amount = 1;
[Tooltip("Current health of the object. Automatically set to MaxHealth on start.")]
public float currentHealth;
[Header("Custom Events")]
[Tooltip("What happens when the player interacts with this object? (e.g. Open a door, light a fire)")]
public UnityEvent onInteract;
[Tooltip("What happens when the object's health reaches 0? (e.g. Spawn a particle effect before destroying)")]
public UnityEvent onBreak;
private void Start()
{
// Initialize current health from the Scriptable Object template
if (data != null && data.isDamagable)
{
currentHealth = data.maxHealth;
}
}
/// <summary>
/// Call this from your weapon scripts or projectiles when they hit this object!
/// </summary>
public void TakeDamage(float damageAmount)
{
if (data == null || !data.isDamagable) return;
currentHealth -= damageAmount;
Debug.Log($"{data.objectName} took {damageAmount} damage! Health remaining: {currentHealth}");
if (currentHealth <= 0)
{
BreakObject();
}
}
private void BreakObject()
{
Debug.Log($"{data.objectName} has broken!");
// Fire off any custom effects defined in the inspector (like spawning wood splinters)
onBreak?.Invoke();
// Destroy the object
Destroy(gameObject);
}
/// <summary>
/// Call this when the player aims at the object and presses the Interact key (e.g. 'E')
/// </summary>
public void Interact()
{
if (data == null || !data.isInteractable) return;
Debug.Log($"Player interacted with {data.objectName}.");
// Fires off custom logic (e.g. calling a script to open a door, or turning on a Torch's light component)
onInteract?.Invoke();
}
/// <summary>
/// Call this when the player walks over the item or picks it up
/// </summary>
public void Pickup()
{
if (data == null || !data.isPickupAble) return;
Debug.Log($"Picked up {amount}x {data.objectName} (Value: {data.valueInGold * amount}g)");
// Here you would add the item to your future Inventory script
// e.g., InventoryManager.Instance.AddItem(data, amount);
// Remove the object from the ground
Destroy(gameObject);
}
}