一段时间后如何从循环中从数组中删除对象

时间:2019-05-25 10:30:39

标签: c# visual-studio unity3d

我想从循环中删除(销毁)我的游戏对象(障碍),这些对象是在一段时间后由random.range随机生成的,但并没有删除。我试图更改“ Destroy(newSelected [ran],5)”的位置,但不起作用。

         private void OnTriggerExit(Collider theCollision)
            {

              if (theCollision.gameObject.tag == "Ob2")
               {
                a = theCollision.transform.position;
                x = a.z + 3f;
                x_ = a.z - 1f;
                startingpoint = a.x;

                for (int i = 8; i <= 64; i += 8)
                {

                    var ran = Random.Range(0, 4);
//selecting gameobjects(hurdles) by default.
                    print(ran);
                    b = new Vector3(startingpoint + i, 0.050f, Random.Range((int)x_, (int)x));
                    if (ran == 2)
                    {

                        newSelected[2]=Instantiate(gameObjects[2], new Vector3(startingpoint + i, 0.050f, a.z), Quaternion.identity);

                        print(x_);
                    }
                    else if (ran != 2)
                    {

                        newSelected[ran]=Instantiate(gameObjects[ran], b, Quaternion.identity);


                    }

                    Destroy(newSelected[ran], 5);
//I want to destroy my gameobjects(hurdles) here that are instantiate after some time.
            } 
      }
     } 
    }

1 个答案:

答案 0 :(得分:0)

您上面的代码将尝试7次以 random 索引为0、1、2或3破坏newSelected数组中的对象。这意味着,例如,它可能试图破坏对象在索引0处多次出现,因此在第一次销毁该对象后会返回空错误。

为避免该错误,在尝试销毁newSelected [ran]之前,应检查其是否为null。

我建议您创建一个单独的组件来处理随机延迟销毁功能,并将其添加到您要实例化的GameObject中。

这是一个快速的C#脚本,可以处理销毁其所附的GameObject:

using UnityEngine;

public class DestroyAfterRandomDelay : MonoBehaviour
{

    [Tooltip("Minimum delay value")]
    public float MinimumDelay = 0f;

    [Tooltip("Maximum delay value")]
    public float MaximumDelay = 4f;

    // keeps track of elapsed time
    private float _elapsedTime= 0;

    // Keeps track of random delay 
    private float _randomDelay;

    // Start is called before the first frame update
    void Start()
    {
        // Sets random delay on start
        _randomDelay = Random.Range(MinimumDelay, MaximumDelay);

        Debug.LogFormat("{0} will be destroyed in {1} seconds!", this.name, _randomDelay);
    }

    // Update is called once per frame
    void Update()
    {

        // Increment time passed
        _elapsedTime += Time.deltaTime;

        // Proceed only if the elapsed time is superior to the delay
        if(_elapsedTime < _randomDelay) return;

        Debug.LogFormat("Destroying {0} after {1} seconds! See Ya :)", this.name, _elapsedTime);

        // Destroy this GameObject!
        Destroy(this.gameObject);

    }
}