问题
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?
回答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)
回答2:
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
来源:https://stackoverflow.com/questions/14529726/search-a-substring-in-an-array-of-strings-in-unityscript