Managing taking damage.
Supposing we have different objects in our game, ships, bases, turrets, cargo pods etc. and projectiles, when a projectile hits something, how will it know what function to call in order for that object to take damage? Knowing that each object has a special manager, that implements an interface IDamageable let's say, and that it's always at the root of the object (but turrets will be children for example) and the collider isn't always in the same object as the manager, how can I handle the damage that the projectile does (along with other special attacks etc)? Also, the managers of each object would inherit from a base manager(if that helps at all)...
Answer by YoungDeveloper · May 27, 2016 at 01:42 PM
Why not implement from Monobehaviour base? On hit try to get the component, if it's not null then remove health. Here's and example.
public class KillableBase: MonoBehaviour {
[SerializeField]private int _health = 100;
public void RemoveHealth(int amount){
health -= amount;
}
}
public class Ship: KillableBase{
//members and methods for ship only
}
Now our ship is somewhere in the game
It gets hit.
int damage = 57; GameObject hitObject; //get our hit from raycast KillableBase killable = hitObject.getComponent<KillableBase>(); if(killable != null){ killable.RemoveHealth(damage ); }
This part i kind of got working, the tricky part is finding the correct $$anonymous$$illableBase that should take damage. As i said in the question, it is not always in the same place as the collider, and there are multiple colliders and $$anonymous$$illableBase derived classes scattered all over an object.
You have to form your own hierarchy logic and stick to it. I usually stick to adding such component to main parent gameobject only. So after collider hit i get it's root by transform.root and process that. Other, but awful solution would be looping all transforms of that trasform and checking all of them.
I understand your concern. I always think the same way (what if...), even if I apply the same logic to every gameobject in the scene. The only way I have come about to appreciate and implement is GetComponentInChildren(true); if you have more than one, GetComponent*s*InChildren. If you are still unsure which gameobject would the message emitter be, a parent or a child, you can access the root transform and apply the aforementioned method. If you know it is a child, you can use GetComponentInParent.
Your answer
Follow this Question
Related Questions
unable to use dontdestroy on load 1 Answer
Trying to get audiosource to play once 1 Answer
MobController 1 Answer
C# enable script component 2 Answers
Dynamic Placement of Object Instantiate using RaycastHit 2 Answers