在這個函數中,我製作了一個循環遍歷孩子並銷燬它們。 問題是,例如,如果我有1個孩子,並且在腳本中的檢查器中,我將孩子的值從1改爲10,那麼它會將10個新孩子添加到已存在的孩子中。所以,我現在已經11然後,如果我將值改爲從10到100,我將有111,如果我變回1,那麼我將有112如何在創建新的對象之前銷燬所有childs對象?
我希望它同時在遊戲運行,如果做些什麼我先改變這個值,然後根據最後一次改變的值,重新創建一次。所以如果當我運行遊戲時的值是10並且我將它改爲100首先刪除10然後添加新100.如果我從10改變爲1,先刪除10然後加1。
我想要什麼一般來說,當遊戲運行時更改_birdscount的值會改變孩子的數量。
在腳本的頂部:在將檢查功能
void Start()
{
if(globalSettings == null)
{
settings = LoadSettings();
globalSettings = settings;
}
else
settings = globalSettings;
InstantiateBirds();
cameraControl.Enabled = !settings.showSettingsWindow;
StartCoroutine(_WatchBirdCount());
}
這時如果值_birdscount改變或不毀:
public CameraControl cameraControl;
public Object birdPrefab;
public Transform birdParent;
private Transform cameraObj;
public Transform[] instancePoints;
public int _birdscount;
在開始功能我添加了一個StartCoroutine孩子們並創建一次:
int prevBirdCount;
List<Transform> transforms = new List<Transform>();
IEnumerator _WatchBirdCount()
{
prevBirdCount = _birdscount;
while(true)
{
if(_birdscount != prevBirdCount)
{
prevBirdCount = _birdscount;
//Do something
foreach (Transform child in birdParent)
{
//child is your child transform
Destroy(child);
}
InstantiateBirds();
}
yield return 0; //Wait a frame before checking again
{
}
}
}
InstantiateBirds()函數t帽子讓孩子的: 我加入到這一功能的行:
sts.BirdsCount = prevBirdCount;
這裏:
void InstantiateBirds()
{
var ip = instancePoints[settings.instancePointNum];
var sts = settings.boidSettings[settings.instancePointNum];
sts.Trace = ip.GetComponent<Trace>();
const float size = 0.1f;
cameraObj = InstantiateBird(ip.position, ip.rotation, sts).transform;
cameraControl.Target = cameraObj;
sts.BirdsCount = prevBirdCount;
MathTools.FillSquareUniform(sts.BirdsCount, delegate (int x, int y)
{
if(x != 0 || y != 0)
InstantiateBird(
cameraObj.position + new Vector3(size * x, size * y, Random.Range(-size, size)),
MathTools.RandomYawPitchRotation(),
sts
);
});
}
,如果它需要的InstantiateBird功能:
private GameObject InstantiateBird(Vector3 position, Quaternion rotation, Boid.Settings boidSettings)
{
var obj = (GameObject)Instantiate(birdPrefab, position, rotation);
var boid = obj.GetComponent<Boid>();
obj.transform.parent = birdParent;
boid.SettingsRef = boidSettings;
boid.DebugSettingsRef = settings.debugSettings;
return obj;
}
首先我改變現在的線sts.BirdsCount = _birdscount;在InstantiateBirds()現在,當它是= _birdscount時,我鍵入值2它將添加2個新的孩子,如果我鍵入5它將添加5個新的孩子。但仍然不是先刪除舊的。它不斷添加新的孩子到已經存在的孩子。 –
你確實改變了'_WatchBirdCount'中的'foreach'循環來說'Destroy(child.gameObject)'? –
它似乎現在正在工作,我的意思是當我鍵入例如11,並且已經有1它會添加新的10然後如果我鍵入5它會保持第一個並添加4.所以關於計數數字似乎是罰款。但由於某種原因,第一個人永遠不會毀滅。如果我輸入例如0,所以第一個將停留。第一個從不摧毀。 –