I’ve a projectile that I want to work for two tags “Enemy” and “Player” but after a bit of Google search: it doesn’t seem like there is a way to tag them both (unless I’m mistaken?) but in that case, then how would I go about changing this part of the script, so that the projectile works on both the enemies and the player, when they are getting shot at?
void OnCollisionEnter (Collision collisionTemp) {
if(collisionTemp.gameObject.tag == "Enemy") {
collisionTemp.gameObject.SendMessage("TakeDamage", damage, SendMessageOptions.DontRequireReceiver);
ContactPoint contact = collisionTemp.contacts[0];
Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
Vector3 pos = contact.point;
Instantiate (lasterHitFXPrefab, pos, rot);
Destroy (gameObject);
}
}
There are many different ways of doing this, but since your question is asking specifically about Tags, I’ll tailor this answer towards the Tag system.
For starters, always use gameObject.CompareTag(string tag)
instead of getting the tag and doing string comparison. This avoids an internal string access and is a minor performance benefit, especially if you have a lot of tag comparisons.
In your projectile class, you could define an array of acceptable target tags, and then when you want to check if it’s a valid hit, compare against that list:
string[] targetTags = new string[] { "Player", "Enemy" };
bool IsTargetTag(GameObject go) {
for (int i = 0; i < targetTags.Length; i++) {
if (go.CompareTag(targetTags*))*
return true;
}
return false;
}
Then in your existing code where you do the string comparison, just slot in IsTargetTag()
et voilà!