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?

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
Joetjah
  • 6,292
  • 8
  • 55
  • 90

2 Answers2

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

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 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. – Joetjah Jan 25 '13 at 20:27
  • Fair enough, I haven't used Unity so I didn't know ;) – Niet the Dark Absol Jan 25 '13 at 20:27
  • 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............. – Joetjah Jan 25 '13 at 20:32
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)
DocMax
  • 12,094
  • 7
  • 44
  • 44