I’m getting a OnTriggerEnter2D event with and object that was just deleted.
I’m using the following code to recycle my enemies:
Destroy(Chunk[0]);
int max = Chunks-1;
float px = FirstX;
for(int i=0;i<max;i++){
Chunk *= Chunk[i+1];*
tChunk = tChunk[i+1];
tChunk*.localPosition = new Vector3(px,0,0);*
px += ChunkWidth;
}
Chunk[max] = (GameObject) Instantiate(Prefab[Current]);
tChunk[max] = Chunk[max].transform;
tChunk[max].parent = tRoot;
tChunk[max].localPosition = new Vector3(px,0,0);
Chunk is an array of GameObjects while tChunk contains its respective transforms. Enemies (colliding objects) are contained inside the Prefabs I’m instantiating. So when I delete the first chunk all child objects are supposed to be deleted too… and they seem to be, since they disappear from the Hierarchy window… but oddly enought, sometimes I get an OnTriggerEnter2D event from the object that was just deleted.
To make sure I inserted some Debug.Log’s in my code and what I get on the console is this:
BackgroundScroll called:
Destroy Enemy1 at: X=-6.57
OnTriggerEnter2D called:
Crash with Enemy1 at: X=-1.57
Since I’m making sure to have only one enemy of each type is on screen at any given time, the previous log referes to the same object.
Now the value of ChunkWidth is 5… that’s why I suspect of the previous code, but I cannot understand why Chunk[0] the deleted one is changing position, and thus fall in the collision range, and even generate a collision event when it no longer exists.
Any Ideas?