106 lines
2.6 KiB
C#

using System.Collections.Generic;
using UnityEngine;
namespace BulletHellTemplate
{
[System.Serializable]
public class DropChance
{
public DropEntity drop; // The drop item
public int chance; // Chance for this drop to occur as an integer
}
public class BoxEntity : MonoBehaviour
{
[Header("Box Settings")]
public int maxHP = 100;
private int currentHP;
[Header("Drop Values")]
public int hpValue;
public int xpValue;
public int goldValue;
[Header("Drop Settings")]
public List<DropChance> dropChances;
[Header("UI Elements")]
public GameObject healthBarUI;
public Transform healthBar;
void Start()
{
currentHP = maxHP;
UpdateHealthBar();
}
void Update()
{
}
public void ReceiveDamage(int damage)
{
currentHP -= damage;
UpdateHealthBar();
if (currentHP <= 0)
{
DestroyBox();
}
}
private void UpdateHealthBar()
{
if (healthBarUI != null && healthBar != null)
{
healthBarUI.SetActive(true);
healthBar.localScale = new Vector3((float)currentHP / maxHP, 1f, 1f);
}
}
private void DestroyBox()
{
DropItem();
Destroy(gameObject);
}
private void DropItem()
{
int totalChance = 0;
foreach (var dropChance in dropChances)
{
totalChance += dropChance.chance;
}
int randomPoint = Random.Range(0, totalChance);
int currentSum = 0;
foreach (var dropChance in dropChances)
{
currentSum += dropChance.chance;
if (randomPoint < currentSum)
{
DropEntity dropItem = Instantiate(dropChance.drop, transform.position, Quaternion.identity);
SetDropValue(dropItem);
break;
}
}
}
private void SetDropValue(DropEntity dropItem)
{
switch (dropItem.type)
{
case DropEntity.DropType.Gold:
dropItem.SetValue(goldValue);
break;
case DropEntity.DropType.Experience:
dropItem.SetValue(xpValue);
break;
case DropEntity.DropType.Health:
dropItem.SetValue(hpValue);
break;
}
}
}
}