【问题标题】:Get gameogject names in array获取数组中的游戏对象名称
【发布时间】:2021-03-29 15:23:26
【问题描述】:

如何通过 if(); 运算符上的名称使用数组中的特定游戏对象? 我现在那个,不能隐式转换类型string[]' to string',但必须是另一种方式?

List <GameObject> cubes = new List<GameObject> ();

private void OnCollisionEnter(Collision coll)
    {
        if (coll.gameObject.tag == "ground")
        {
            coll.gameObject.GetComponent<Renderer>().material.SetColor("_Color", Color.red);


            cubes.Add (coll.gameObject);

            string[] ar1 = {"a1","a2" ,"a3","a4"};

            if (cubes.Count > 4) {

                foreach(GameObject go in cubes){

                    if (go.name == ar1) {

                        Debug.Log ("PASSED");
                    }

                }

【问题讨论】:

  • 这个有点不清楚。
  • 当数组中的特定游戏对象为 OnCollisionEnter 时,必须工作。
  • 我想在'if()'操作符的数组中获取游戏对象名称

标签: c# arrays unity3d


【解决方案1】:

阅读您的 cmets 后,我明白您在问什么: 如何检查ar1 中指定名称的所有对象是否都在cubes 列表中?

我会这样做:

List<string> ar1 = new List<string>() {"a1","a2","a3","a4"};
List<string> cubeNames = new List<string>();

foreach(GameObject go in cubes) {
    cubeNames.Add(go.name);
}

if (aIsSubsetOfB(ar1, cubeNames)) {
    Console.WriteLine("PASSED");
}

bool isASubsetOfB(List<string> a, List<string> b) {
    foreach(string element in a) {
        if (!isAinB(element, b)) {
            return false;
        }
    }
    return true;
}

bool doesBcontainA(string a, List<string> b) {
    foreach(string element in b) {
        if (element == a) {
            return true;
        }
    }
    return false;
}

为了方便和代码清晰,我添加了 isASubsetOfBdoesBcontainA 方法

【讨论】:

  • 这在 OnCollisionEnter 数组中的一个游戏对象时起作用。如果 OncollisionEnter 我想获取数组中的所有游戏对象
  • 那么您想检查名称在ar1 中的多维数据集是否在您的cubes 列表中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-13
  • 1970-01-01
  • 2021-08-23
  • 2015-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多