- Home /
Looking for a Better Way to check Multiple Tags
Hello everyone, I've got a situation where I need to check an objects tag to determine what type of "surface"/material the object represents so I can play a sound when the player lands on it. It is simple enough, but, due to the way the tag structure is set up, I am ending up with very long IF statment conditions ex:
else if (other.gameObject.tag == "tag1" || other.gameObject.tag == "tag2"|| other.gameObject.tag == "tag3"|| other.gameObject.tag == "tag4" || other.gameObject.tag == "tag5")
{
if (!audioSource.isPlaying)
{
audioSource.clip = RandomizeAudioClip (landingHardSurfaceArray);
audioSource.Play();
}
}
So I was wondering what the smarter / cleaner way of doing this would be. Any suggestions are appreciated
Answer by jonSG · Apr 14, 2014 at 08:28 PM
using System.Linq has a quick and dirty option for you:
string[] HardSurfaceTags = {"tag1", "tag2"};
if ( HardSurfaceTags.Contains(other.gameObject.tag) ){
print (other.gameObject.name + " is a hard surface" );
}
If you're doing this a lot, you can also make an extension class with the method public static bool IsIn<T>(this T keyObject, params T[] collection) { return collection.Contains(keyObject); }
, (and make the containing class public static as well).
Then you can use it like if (mainObject.IsIn(obj1, obj2, obj3, obj4, obj5)) {}
Answer by Scrapy_ · Apr 14, 2014 at 08:17 PM
can get it a bit shorter like this.
someTag = other.gameObject.tag;
else if (someTag == "tag1" || someTag == "tag2"|| someTag == "tag3"|| someTag == "tag4" || someTag == "tag5")
{
if (!audioSource.isPlaying)
{
audioSource.clip = RandomizeAudioClip (landingHardSurfaceArray);
audioSource.Play();
}
}
I appreciate the idea, but what jonSG proposed is more of the type of solution I'm looking for.
Your answer
![](https://koobas.hobune.stream/wayback/20220613142719im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
C# Declaring Variables Within If Statements 2 Answers
C# How to Check If a Gameobject's tag doesn't equal a Specific Tag 3 Answers
How to check if there are 10 objects with the same tag in the scene 2 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers