Switch & String.Contains()

This might be a silly question.

Is it possible to use switch on the string.Contains("") parameter? It returns a bool so obviously this wouldn’t work

string name = collision.gameObject.name;
  
switch (name.Contains(""))
    case "someString":
        //Do stuff and things.
        break;
    default:
        break;

but hopefully that conveys what I’m trying to accomplish.

I instantiate a bunch of item pickups of different types all tagged as "Item" and essentially want to identify the item on collision. But names by default are object, object (1), object (2), ect. .Contains() seems like the way to go but I could be going about this all wrong idk. So far the only solution I see is to use a bunch of else if statements for each item type and that’s what a switch statement is for XD

There might be some syntax errors as I wrote this without a C# IDE.

string name = collision.gameObject.name;
if (name.Contains(" ("))
   name = name.Substring(0, name.IndexOf(" ("));

switch (name) {
    case "object":
        // ...
        break;
    case "strawberry":
        Eat(collision.gameObject);
        break;
}

Actually I am still prefering IFs, because I am not used to string switches (which just recently came to Java), but that is a matter of taste, I guess. :slight_smile:

Using C# v7 this is now possible, so if you’re using Unity 2018.3 or later or one of the earlier versions that allows .NET v4.0 you can use a switch statement with pattern matching. Here is some example code.

void OnCollisionEnter(Collision other)
{
	// Dectect and handle collisions
	switch (other.gameObject.name)
	{
		case string a when a.Contains("Wall"):
			bouncePos = transform.position;
			bounce = true;
			break;
		case string a when a.Contains("Door"):
			bouncePos = transform.position;
			bounce = true;
			break;
		case string a when a.Contains("Stairs"):
			distanceToMove = 0.0f;  // Disable moving before changing levels
			StartCoroutine(ChangeLevel(other.gameObject.GetComponent<Stairs>().NewRelativePosition));
			distanceToMove = 4.0f;  // Enable moving after changing levels
			break;
		case null:
			new System.ArgumentNullException(nameof(other));
			break;
	}
}

Thank you for the string search guidelines, that worked perfectly!