Trouble checking for multiple tags using a single conditional statement

Hey guys,

So currently I am on the “project boost” section and I started experiencing a problem and I can’t see what I am doing wrong… Basically my problem is that I declared an array of string as a member variable:

[SerializeField] string[] friendlyTags = {""};

This enabled me to edit the array size and the values from within the inspector window. The weird thing is that this part seems to work, I know this because after adding values within the inspector and adding a print statement within the collision method it printed the tag names fine and as expected. I checked the type and and that returns System.String which is good as far as I am aware.

Here’s the code of my collision method:

    private void OnCollisionEnter(Collision collision)
    {
        foreach (string friendlyTag in friendlyTags)
        {
            if (collision.gameObject.tag != friendlyTag)
            {
                //print(collision.gameObject.tag);
                print(friendlyTag.GetType()); // returns System.String
            }
        }
           
    }

I have also tried doing something as follows:

 if (collision.gameObject.tag != "LandingPad" || collision.gameObject.tag != "SpawnPoint")
            {
                //print(collision.gameObject.tag);
                print(friendlyTag.GetType()); // returns System.String
            }

This also did not work, weirdly enough if I checked only for a single tag: if (collision.gameObject.tag != "LandingPad") it works fine. I am really lost and would really appreciate if someone could tell me what I am doing wrong.

Thanks :slight_smile:!

I just realised my mistake :flushed:

Solved it by converting the array to a list and using a built-in method Contains() on the list.

[SerializeField] List<string> friendlyTags = new List<string>();

//some code

private void OnCollisionEnter(Collision collision)
    {
        if (!friendlyTags.Contains(collision.gameObject.tag))
        {
            print(collision.gameObject.tag);
        }    
    }

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms