So I want to create an attack Script that removes health, when something is inside of it.
This is the attack-trigger:
void OnTriggerStay(Collider collider)
{
if (collider.gameObject.tag == "Enemy")
{
var ph = collider.gameObject.GetComponentInParent<PlayerHealth>();
ph.ModifyHealth(-1);
}
}
and this is the Health script attached to the triggered object:
public class PlayerHealth : MonoBehaviour
{
[SerializeField] static int maxHealth = 100;
[SerializeField] float refillRepeatRate = 0.2f;
public int currentHealth;
public static event Action<float> OnHealthPercentChange;
void Awake()
{
currentHealth = maxHealth;
}
public void ModifyHealth(int amount)
{
if (currentHealth <= 0) return;
currentHealth += amount;
float currentHealthPct = (float)currentHealth / (float)maxHealth;
OnHealthPercentChange(currentHealthPct);
}
Originally I thought that every adding a script to a gamObject automatically instantiates the class and by using GetCompponent you could access the instance. But this is not the case. Instead the health gets removed globally on all gameObjects like it would be a static.
Would be making the HealthScript a ScriptableObject and then using “new HealthScript” in a different script attached to the gameObject the ideal way to do this? I watched this Video (
) and he directly attached it to the gameObject so I thought it was the “correct” way.