【问题标题】:Use last added GameObject to the array/list使用最后添加的游戏对象到数组/列表
【发布时间】:2017-04-12 14:46:06
【问题描述】:

我在 Unity 中使用 C#。我在数组中有 3 个不同的 GameObjects,我想使用这样的 if 语句将最后一个生成/添加的对象添加到列表中:If object 1 spawned then ...
我该如何进行这项工作?这是代码:

public GameObject[] arrows;
public float interval = 5;
private List<GameObject> myObjects = new List<GameObject>();

// Use this for initialization
void Start()
{
    InvokeRepeating("SpawnArrow", 0f, interval);
}

void SpawnArrow()
{
    if (myObjects.Count > 0)
    {
        Destroy(myObjects.Last());
        myObjects.RemoveAt(myObjects.Count - 1);
    }
    GameObject prefab = arrows[UnityEngine.Random.Range(0, arrows.Length)];
    GameObject clone = Instantiate(prefab, new Vector3(0.02F, 2.18F, -1), Quaternion.identity);

    myObjects.Add(clone);
}

【问题讨论】:

    标签: c# arrays list unity3d


    【解决方案1】:

    首先,为进一步的逻辑(你的 if 语句)保留随机整数的值:

    void SpawnArrow()
    {
        if (myObjects.Count > 0)
        {
            Destroy(myObjects.Last());
            myObjects.RemoveAt(myObjects.Count - 1);
        }
        // Here hold up the value to use in your if statement
        int randomIndex = UnityEngine.Random.Range(0, arrows.Length);
    
        GameObject prefab = arrows[randomIndex];
        GameObject clone = Instantiate(prefab, new Vector3(0.02F, 2.18F, -1), Quaternion.identity);
    
        myObjects.Add(clone);
    
        // your if statement 
        if ( randomIndex == 1 )
        {
            // your logic
        }
    } 
    

    【讨论】:

      【解决方案2】:

      你可能想看看使用Stacks。这是一个后进先出数据结构的例子,如果你说想要的话听起来很完美:

      使用最后一个对象它生成/添加到列表中

      使用堆栈的示例:

      using System;
      using System.Collections;
      
      namespace ConsoleApplication1
      {
          class Program
          {
              static void Main(string[] args)
              {
                  Stack stack = new Stack();
      
                  stack.Push("First Item");
                  stack.Push("Second Item");
      
                  Console.WriteLine(stack.Pop());
                  Console.WriteLine(stack.Pop());
      
                  Console.ReadKey();
              }
          }
      }
      

      输出:

      Second Item
      First Item
      

      请注意,当项目被添加(推送)到堆栈然后从堆栈中移除(弹出)时,您将首先获得添加到堆栈中的最后一个项目。

      A useful link on how to use stacks

      【讨论】:

      • 数据结构ftw.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      相关资源
      最近更新 更多