Detroy() deleting itself and another
I have this method that is called on the game start and is part of my map generation.
void GeoGen(GameObject[] rndObj, GameObject obj02, int minAmount, int maxAmount)
{
int amount = Random.Range(minAmount, maxAmount);
Debug.Log(amount);
for (int a = 0; a < amount; a += 1)
{
int rndGeo = Random.Range(0, tempS);
float tempX = rndObj[rndGeo].transform.position.x;
float tempY = rndObj[rndGeo].transform.position.y;
Instantiate(obj02);
obj02.transform.position = new Vector2(tempX, tempY);
Destroy(rndObj[rndGeo]);
}
}
As you can see in this picture, the square on the far right edge is missing and does not have a obj02 in it's place (in this case, the tree squares). I'm not sure what I am doing wrong. Any help will be appreciated.
Did you intend to attach an image? If so, I don't see it.
Answer by NoseKills · Jul 03, 2016 at 09:19 PM
I assume obj02 is not a scene object?
You make a clone of obj02 with Instantiate. You leave the clone wherever it happens to be created (the initial position on obj02)
Then you set the position of obj02 to be the same as the object you destroy and you call Destroy
On the next iteration of the loop you do the same, but now position of obj02 is the same as the object you destroyed in the previous iteration and this second clone appears in that spot, filling the gap you made then.
Because of this, the last destroyed piece doesn't get replaced and the first created clone is left wherever obj02's position was initially.
You need to position the created clone to fill the gap, not obj02
var clone = Instantiate(obj02);
clone.transform.position = new Vector2(tempX, tempY);
Your answer
![](https://koobas.hobune.stream/wayback/20220612084151im_/https://answers.unity.com/themes/thub/images/avi.jpg)