C# 如何动态重置场景中的对象数?

C# 如何动态重置场景中的对象数?,c#,dynamic,unity3d,C#,Dynamic,Unity3d,我正在尝试构建这个游戏: 用户通过GUI设置一个名为samplesize的整数和一个名为ylocation的数字。因此,将在场景中显示完全采样的球体,沿x轴等距排列,并向上移动到Y位置 如果用户为samplesize和ylocation输入新值,则场景将更改以反映新数量的球体和位置 以下是我的问题: 当我设置一个samplesize时,上一个场景中留下的多余球体不会消失。我怎么做尿布? 例如,如果一个场景有1000个球体,我将samplesize重定义为5,然后单击“确定”,那么我只想看到5个球

我正在尝试构建这个游戏:

用户通过GUI设置一个名为samplesize的整数和一个名为ylocation的数字。因此,将在场景中显示完全采样的球体,沿x轴等距排列,并向上移动到Y位置

如果用户为samplesize和ylocation输入新值,则场景将更改以反映新数量的球体和位置

以下是我的问题: 当我设置一个samplesize时,上一个场景中留下的多余球体不会消失。我怎么做尿布? 例如,如果一个场景有1000个球体,我将samplesize重定义为5,然后单击“确定”,那么我只想看到5个球体,而不是1000个

我如何使游戏开始时没有球体。在设置samplesize并单击“确定”之前,我不希望任何球体出现在场景中。 但是统一C?首先将所有1000个球体放置在位置0,0,0处。我如何阻止Unity这样做

下面是我为数据输入设置GUI的代码

using UnityEngine;
using System.Collections;

public class ButtonText : MonoBehaviour
{   
    private bool defineModel = false;
    string beta0 = "" ,  beta1 = "";
    public float  ylocation ;
    public int samplesize=0 ;

    void OnGUI()
    {
        if (!defineModel) {
            if (GUI.Button (new Rect (0, 0, 150, 20), "Define a model"))
                defineModel = true;
         } else {  
            beta0 = GUI.TextField (new Rect(10, 10, 50, 25), beta0, 40);
            beta1 = GUI.TextField (new Rect(10, 40, 50, 25), beta1, 40);

            if (GUI.Button (new Rect (300, 250, 100, 30), "OK")) {
                    samplesize = int.Parse(beta0);
                    ylocation = float.Parse(beta1);
                    defineModel = false;
                    return; 
            }
        }
    }
}
这是我绘制场景的代码

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

public class SphereManager : MonoBehaviour
{
    public List<GameObject> spheres; // declare a list of spheres
    void Awake () {

        for (int i = 0; i < 1000; i++) {
            GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); // Make a new sphere
            Rigidbody gameObjectsRigidBody = sphere.AddComponent<Rigidbody>(); // Add the rigidbody.
            gameObjectsRigidBody.useGravity = false; // turn off the sphere's gravity.
            sphere.collider.enabled = false;         // remove the collider
            spheres.Add(sphere);                    // add the sphere to the end of the list


        }
    }

    void Update()  
    {       
        int n = GetComponent<ButtonText> ().samplesize;
        float ylocation = GetComponent<ButtonText> ().ylocation;

        for(int i=0; i<n; i++) {
            spheres[i].transform.position = new Vector3(i, ylocation, 0); // reposition the sphere
        }       
     } 
}

可以切换球体的显示

    for(int i=0; i < spheres.Count; i++) { // now iterating all
        spheres[i].SetActive(i < n); // show/hide sphere
        if (spheres[i].active) // only reposition active spheres
            spheres[i].transform.position = new Vector3(i, ylocation, 0); // reposition the sphere
    }