- Home /
Question by
Chocolade · May 30, 2017 at 06:27 AM ·
c#scripting problemscript.
How can i first destroy twice the objects then to create twice the objects ?
Twice or more inside the loop depending the instantiateobjects Length. But what i mean is that every time the toggleOnOf is false first make all the DestroyObjects() part in the loop. Then make the generateObjectOnTerrain().
I mean on this part:
instantiateobjects[i].DestroyObjects();
instantiateobjects[i].generateObjectOnTerrain();
destroyed = true;
For example if instantiateobjects length is 3 the first make 3 times the DestroyObjects() and then make 3 times the generateObjectOnTerrain(). Only when it's in the else part when toggleOnOf is false.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GenerateObjectsButton : MonoBehaviour
{
[SerializeField]
private InstantiateObjects[] instantiateobjects;
private bool toggleOnOf;
public Toggle toggle;
public bool destroyed = false;
private void Start()
{
toggle.onValueChanged.AddListener((value) =>
{
MyListener(value);
});
}
public void MyListener(bool value)
{
if (value)
{
//do the stuff when the toggle is on
toggleOnOf = true;
}
else
{
//do the stuff when the toggle is off
toggleOnOf = false;
}
}
public void OnButton()
{
for (int i = 0; i < instantiateobjects.Length; i++)
{
if (toggleOnOf == false)
{
if (instantiateobjects[i] != null)
instantiateobjects[i].generateObjectOnTerrain();
}
else
{
if (instantiateobjects[i] != null)
{
instantiateobjects[i].DestroyObjects();
instantiateobjects[i].generateObjectOnTerrain();
destroyed = true;
}
}
}
}
}
Comment
Best Answer
Answer by Ali_Jaffer · May 30, 2017 at 06:33 AM
It is Better to Use Object polling than Instantiate and destroying https://unity3d.com/learn/tutorials/topics/scripting/object-pooling
Your answer
![](https://koobas.hobune.stream/wayback/20220612123102im_/https://answers.unity.com/themes/thub/images/avi.jpg)