Search a substring in an array of Strings in unityscript

江枫思渺然 提交于 2019-12-11 15:06:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!