OnTriggerEnter find damage that other object should deal C#
Hello. I have different space ships that will eventually have different shots with different amounts of damage, as well as obstacles that will cause damage when they hit the ships. My question is, how do I get a ship to find out what the damage of the object that hit it with OnTriggerEnter is, and then subtract that amount from the ship's health?
Answer by KdRWaylander · Nov 20, 2015 at 02:52 PM
If i understand correctly what you say, you want different objects to deal different amounts of damage to the ship ?
If you have object A and B, ship S:
First solution would be a script on your objects, when a collider hits the collider of your object, if the tag of the object that has the collider is "Ship" → deal xx damage. You write one script for each kind of object or a single script for all objects and when the ship hits the collider you decide how much damage you deal with a swtch case on the name of the object.
Second solution would be the reverse situation, you have a script on your ship, if it hits a collider, it checks the tag of the object that bears the collider, if this tag is "object A", substract x health point to the ship, if the tag is "object B", ...
Yes. That is exactly what I wanted. Thank you Waylander.
Answer by Wimmydittle · Nov 22, 2015 at 09:59 PM
Now that I think about it, I will probably eventually want to have upgrades on the ships, and I would really rather not make a bunch of different ship that are the exact same except for the tags. Any answers? I was thinking about the possibility of accessing a script that all ships have, and a variable (like CurrentHealth or something) that all ships have through GetComponent, and that every time someone starts the game, their ship automatically adjusts to their upgrades. How would accessing a script through GetComponent from an object that triggered a collider work?
What if I do something like the following, where every game object has a script called AccessibleScript and a variable called Damage?
void OnTriggerEnter(Collider other) { float Damage = other.gameObject.GetComponent().Damage; CurrentHealth =- Damage; }
I just checked the script and it worked! Thanks for your help!
Your answer
![](https://koobas.hobune.stream/wayback/20220612045734im_/https://answers.unity.com/themes/thub/images/avi.jpg)