cannot destroy transform

public Object firstPiece;

firstPiece = Instantiate(levelPieces[startinglevelPiece],levelPieceSpawnPointL.transform.position, levelPieceSpawnPointL.transform.rotation);

Destroy(firstPiece);

These are the three line where I use the firstpiece variable directly and yet every time I go to destroy it I get this error "Can't destroy Transform component. If you want to destroy the game object please call 'Destroy' on the game object instead. Destroying the transform component is not allowed." I have tried casting it as a game object and I have tried everything besides directly tagging the object and destroying the objects with that tag, however I KNOW this should be able to work simply like this, what the hell am I doing wrong, am I high or missing some glaring problem (and I have tried changing the "public Object firstPiece;" line to GameObject that gives me lots more errors and problems than it fixes

I used Marowi's advice and it worked. But hey, it IS confusing, cause in the script reference it doesn't explicitly says that you can access the gameObject through the transform. Anyway, thanks Marowi.

1 Answer

1

I bet firstPiece is a Transform. Your code "public Object firstPiece;" then casts it to an Object which indeed does not have a ".gameObject" property. This also explains why your GameObject cast did not work...

Destroy can destroy components or entire game objects. However, you cannot remove the transform component of a game object which is why you got your initial error.

instead of:

Destroy(firstPiece);

try:

public Object firstPiece;
firstPiece = Instantiate(levelPieces[startinglevelPiece],levelPieceSpawnPointL.transform.position, levelPieceSpawnPointL.transform.rotation);
Destroy( (firstPiece as Transform).gameObject );

but that code is not pretty. You might want to fix your "public Object firstPiece;" line and post a question about those errors...you probably don't need to cast your Transform to an Object, which forces you to cast it back to a Transform and access the gameObject to destroy it.

if you need firstPiece to not be destroyed, do not destroy it. Just remove the entire destroy line. You need to post the public object errors in a new question. The forums are the place for an elaborate detailed discussion.