Problem
I have a set of various objects on my map that I would like to make destructible. Basically, they are split into 3 parent objects - plants, buildings and moving objects. Each parent contains 100+ children. So, if I shoot an object or objects, it/they should suffer certain amount of damage, and if the damage is critical then get destroyed.
So, I have created a single script called Damageable and added it to every child described in the previous paragraph as below:
Damageable.cs
public class Damageable : MonoBehaviour
{
private float m_CurrentHealth;
private bool m_Destroyed;
...
public void TakeDamage(float amount)
{
m_CurrentHealth -= amount;
if (!m_Destroyed && m_CurrentHealth <= 0f)
{
HandleDeath();
}
}
...
}
Then, in my ShellHit script, I retrieve a list of affected Damageable objects and cause them damage via TakeDamage method.
ShellHit.cs
public class ShellHit : MonoBehaviour
{
...
private void OnTriggerEnter(Collider other)
{
Collider[] colliders = Physics.OverlapSphere(transform.position, m_ExplosionRadius, m_DamageableMask);
foreach (Collider collider in colliders)
{
Rigidbody targetRigidBody = collider.GetComponent<Rigidbody>();
targetRigidBody = collider.GetComponent<Rigidbody>();
if (!targetRigidBody)
{
continue;
}
targetRigidBody.AddExplosionForce(m_ExplosionForce, transform.position, m_ExplosionRadius);
Damageable damageable = targetRigidBody.GetComponent<Damageable>();
if (!damageable)
{
continue;
}
float damage = CalculateDamage(targetRigidBody.position);
damageable.TakeDamage(damage);
...
}
}
...
}
Question
Is it a common practice in Unity what I'm doing by adding the same script to every game object or is there a more common/efficient way of doing the same? For instance, by adding the script to a parent object and make it handle the damage for its children.