Question by
storageapplet · Oct 20, 2021 at 12:27 PM ·
gameobjectinstantiatetransformconversion
Instantiated objects can't convert to GameObjects
Hi all, so I am trying to clear all instantiated objects from scene. So, I am putting all of the instantiated objects in a list, and destroy them in a loop. My code currently looks like this:
private List<GameObject> arlist = new List<GameObject>();
private float f;
public void PerlinGen()
{
for (int x = (int)this.transform.position.x-500; x <= (int)this.transform.position.x+500; x+=10)
{
for (int z = (int)this.transform.position.z-500; z <= (int)this.transform.position.z+500; z+=10)
{
f = Mathf.PerlinNoise((x+500f)/1000f,(z+500f)/1000f);
GameObject k = (GameObject)Instantiate(prefab, new Vector3(x, Convert.ToSingle(Math.Round(f,2))*1000, z), Quaternion.identity);
arlist.Add(k);
}
}
}
private float time = 30f;
public float interpolationPeriod = 2f;
public void DestroyStuff()
{
foreach (GameObject cube in arlist)
{
Destroy(cube);
}
arlist.Clear();
}
void Update() {
time += Time.deltaTime;
if (time >= interpolationPeriod) {
time = 0.0f;
Debug.Log("ready");
DestroyStuff();
PerlinGen();
}
}
Well, Unity says you can't convert from Transform to GameObject, specifically in this line:
GameObject k = (GameObject)Instantiate(prefab, new Vector3(x, Convert.ToSingle(Math.Round(f,2))*1000, z), Quaternion.identity);
I tried to use as, but Unity raises
Assets\worldGen.cs(21,32): error CS0039: Cannot convert type 'UnityEngine.Transform' to 'UnityEngine.GameObject' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
So,basically I tried fixes on the Internet but to no avail. Can you help me please?
Comment