0

我正在尝试在字符串数组中搜索子字符串。我正在使用以下代码(在 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;
       }
    }
}

问题是,Debug.Log 显示Boundary(Clone). 我已包含Boundary在数组中obstacles。下面的代码不应该设置frontAvailable为false吗?还是我在这里犯了错误?

4

2 回答 2

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

于 2013-01-25T20:23:27.707 回答
1

除了 Kolink 的答案之外,您if正在寻找Boundary(clone)的开头Boundary,而不是相反的方式。我想你正在寻找:

if (hitFront.collider.gameObject.name.IndexOf(obstacles[i]) >= 0)
于 2013-01-25T20:26:30.290 回答