如何在创建新对象之前销毁所有对象?

时间:2017-05-20 19:55:14

标签: c# unity3d unity5

我想要做的是,只有当我在检查器中更改要创建的对象数量时,首先销毁所有现有对象(如果有),然后创建新数量的对象。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

    [ExecuteInEditMode]
    public class InstantiateObjects : MonoBehaviour
    {
        public GameObject prefab;
        public Terrain terrain;
        public float yOffset = 0.5f;
        public int objectsToInstantiate;
        public bool parent = true;

        private float terrainWidth;
        private float terrainLength;
        private float xTerrainPos;
        private float zTerrainPos;
        private int numberOfObjectsToCreate;
        private GameObject objInstance;

        public void Start()
        {
            //Get terrain size
            terrainWidth = terrain.terrainData.size.x;
            terrainLength = terrain.terrainData.size.z;

            //Get terrain position
            xTerrainPos = terrain.transform.position.x;
            zTerrainPos = terrain.transform.position.z;

            numberOfObjectsToCreate = objectsToInstantiate;
            generateObjectOnTerrain();
        }

        private void Update()
        {
            if (numberOfObjectsToCreate != objectsToInstantiate)
            {
                for (int i = 0; i < objectsToInstantiate; i++)
                {
                    Destroy(objInstance);
                }
                    generateObjectOnTerrain();
            }

        }

        public void generateObjectOnTerrain()
        {
            for (int i = 0; i < objectsToInstantiate; i++)
            {
                //Generate random x,z,y position on the terrain
                float randX = UnityEngine.Random.Range(xTerrainPos, xTerrainPos + terrainWidth);
                float randZ = UnityEngine.Random.Range(zTerrainPos, zTerrainPos + terrainLength);
                float yVal = Terrain.activeTerrain.SampleHeight(new Vector3(randX, 0, randZ));

                //Apply Offset if needed
                yVal = yVal + yOffset;

                //Generate the Prefab on the generated position        
                objInstance = Instantiate(prefab, new Vector3(randX, yVal, randZ), Quaternion.identity);
                objInstance.name = "Teleportation Booth";
                if (parent)
                    objInstance.transform.parent = this.transform;
            }
        }
    }

这是Inspector中用于设置要创建的对象数的变量:

public int objectsToInstantiate;

如果在检查器中更改了要创建的新对象数,则此变量应该是帮助以检查是否有任何更改:

private int numberOfObjectsToCreate;

更新功能中的代码但它什么也没做。当我在检查员中输入新值时,它没有改变任何东西。

1 个答案:

答案 0 :(得分:-1)

Destroy(objInstance);更改为DestroyImmediately(objInstance);应该有效。

但是,在update中删除和添加新对象并不是一个好主意。您可以尝试维护一个对象池来添加/删除特定对象,并且只有当许多对象在一个操作中删除/添加时,您才应该进行批处理。