- Home /
How do I make an Object Hirarchy - I want a performant way to check if an object is an Enemy and or a specific type of enemy
Hi, I want a way to specify that an Object is a member of a Category and a subcathegory.
For example i have an Astroid that is a type of enemy, and so far it has the tag "enemy" by wich i check in one script if if it is a type of enemy, but if I now want to check in a different script if its a type of astroid I can't simply assign a second tag wich is kind of anoying. How would i go about structuring Objects in categorys and sub cathegorys like that ?
Answer by jamal54312 · Feb 27, 2018 at 10:10 PM
Instead of tags, I'd recommend making use of subclassing. Have a base class called enemy, and have all enemy types inherit from it : Asteroid:Enemy, Rock:Enemy, etc..
using UnityEngine;
public class Enemy : MonoBehaviour {
public virtual string GetType(){
return "UNDEFINED";//Override this result.
}
}
using UnityEngine;
public class Asteroid : Enemy {
public override string GetType(){
return "Asteroid";//
}
}
In your game handler, where you do this checking you'd check the "Enemy"'s GetType() instead of the "GameObject"'s tag.
Thanks for your answer. Ok I know about inheritance but this doesnt work with blueprits or does it? I mean I have an astroid blueprint that i want to spawn, I can make the script on it inherit from the base class enemy, but then i would be back to having to grab the script of the Object by type each time I want to check if its an enemy or an astroid, wich is not verry performant i believe.
No, you don't have to grab the specific script, that's why it has a virtual GetType()
that tells you what type it is (you can even use the returned string in a switch-case).
A very similar approach that does not require getting the exact type (not even as string) is if you declare virtual functions (or even better, abstract) that pass to enemy the concrete types it needs to react to (for example Player or Shot). That way you can implement handling specific to each type.
Okay those are some great suggestions, thanks verry much!
Answer by ShadyProductions · Feb 27, 2018 at 09:27 PM
https://answers.unity.com/questions/21664/is-it-possible-to-have-multiple-tags-or-the-like-o.html
Here are several ways displayed as answers in how you can do this.
the link is verry interesting i think I'll do do the empty gameObject as Tag thing because that way I can simply do this if (Object.transform.Find("Astroid") != null)
And it'll just search one transform wich would have no big performance Impact, would it ?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Making a bubble level (not a game but work tool) 1 Answer
An OS design issue: File types associated with their appropriate programs 1 Answer
How do I force a GameObject with children to collapse and expand in the hierarchy view? 1 Answer