How to delete an instantiated GameObject
I'm developing a board game that operates on a grid layout. In order to move, the gameobject should re-instantiate itself in the new position (for example, if you move up, the gameobject is re-instantiated in the y+1 position and the previous gameobject, referring to your previous position, should be deleted). My question is, how do I delete the object in the previous position?
My method currently looks like this:
public void move(String direction)
{
if (direction.Equals("up")) {
playerPosition.y += 1;
Destroy(furbot, 0f);
Instantiate(furbot, playerPosition, Quaternion.identity);
}
}
Currently, the new position is displayed correctly, but the clones in the previous positions are not deleted.
Why creating + deleting the object while you can simply move (teleport) it?
Instantiating and destroying objects are operations quite heavy for the device.
Answer by dev99pro · Jul 17, 2018 at 06:43 PM
change your script to :
public void move(String direction)
{
if (direction.Equals("up")) {
playerPosition.y += 1;
Destroy(furbot, 0f);
Gameobject a = Instantiate(furbot, playerPosition, Quaternion.identity);
Destroy(a);
}
}
Just tried that, now the new object is not even created and the console says "Destroying assets is not permitted to avoid data loss. If you really want to moreve an asset use DestroyImmediate(theObject, true);"
But thanks for the contribution anyway!
Any other suggestions?
What version of unity are you using? deleting instantiated object should always work like this: GameObject a = Instantiate (somePrefab, Vector3.zero, Quaternion.identity); Destroy (a);
Answer by LeeJBaxter · Jul 24, 2018 at 01:16 PM
Try this...
public void move(String direction)
{
if (direction.Equals("up")) {
playerPosition.y += 1;
GameObject newFurbot = Instantiate(furbot, playerPosition, Quaternion.identity);
Destroy(furbot);
furbot = newFurbot;
}
}