0

I'm trying to search a substring in an array of Strings. I'm using the following code (in Unity3):

var obstacles = ["Border", "Boundary", "BoundaryFlame"];
var frontAvailable = true;
var leftAvailable = true;
var rightAvailable = true;
var hitFront: RaycastHit;
if (Physics.Raycast(transform.position, transform.position + transform.forward, hitFront, 1.5)) {
    Debug.Log("I hit this in front: ");
    Debug.Log(hitFront.collider.gameObject.name);
    for (var i = 0; i < obstacles.length; i++)
    {
       if (obstacles[i].IndexOf(hitFront.collider.gameObject.name) > -1)
       {
          Debug.Log("Hit in front!");
          frontAvailable = false;
       }
    }
}

The problem is, the Debug.Log shows Boundary(Clone). I've included Boundary in the array obstacles. Shouldn't below code set frontAvailable to false? Or did I make a mistake here?

2 Answers 2

1

In addition to Kolink's answer, your if is looking for Boundary(clone) at the beginning of Boundary, rather than the other way around. I think you're looking for:

if (hitFront.collider.gameObject.name.IndexOf(obstacles[i]) >= 0)
Sign up to request clarification or add additional context in comments.

Comments

1

I think you need indexOf, not IndexOf. Assuming you're talking about the native string function.

In addition, indexOf returns -1 if there is no match, 0 if the match is at the start, 1, 2, 3... for further positions. So you need > -1 instead of > 0

3 Comments

You are correct, it should be -1. I had that at first but changed it later for testing. It still doesn't work :( As for IndexOf, apperantly in Unity, I have to use the capital I. Else it doesn't recognize the method.
Fair enough, I haven't used Unity so I didn't know ;)
It is still JavaScript so I don't know where it's coming from. I was stuck on that exact same issue for almost an hour yesterday.............

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.