Cannot Destroy() object, created via GameObject.CreatePrimitive (others destroyed as should)

Hi all. I’m completely new to Unity, installed it yesterday.
I tried to create a cube via GameObject.CreatePrimitive(PrimitiveType.Cube); and then destroy it. And it don’t disappears. When I doing the same code with object, placed on scene in editor or with object, gained from Instantiate, it destroys them as should.

Sample code to reproduce bug.

var tmp : GameObject;
function Update ()
  if(Input.GetKey(KeyCode.Z))
  {   
    tmp = GameObject.CreatePrimitive(PrimitiveType.Cube);      
  };
  if(Input.GetKey(KeyCode.X))
  {              
    UnityEngine.GameObject.Destroy(tmp.gameObject);      
  };
  if(Input.GetKey(KeyCode.C))
  {              
    UnityEngine.GameObject.Destroy(gameObject); 
  };
}

if I add it to object on scene, C deletes the object, but X do not delete the cube created by Z.

Hope for your help!

It’s not a bug, or rather not a Unity bug; your code has several problems. First, the code won’t do anything because you forgot a { after function Update (). If you’ll notice, the script won’t compile. Once you fix that, it sort of works, though you should replace GetKey with GetKeyDown, since otherwise it will spawn cubes every frame the key is down. Even with GetKeyDown, it’s not ideal, since “tmp” is always a reference to the latest cube spawned, so destroying tmp only removes that reference, not any of the other cubes that may have been spawned.

Unrelated, you should remove references to UnityEngine, since that’s automatically imported anyway. Also you can remove GameObject since Destroy inherits from Object. In other words, replace “UnityEngine.GameObject.Destroy” with just “Destroy”. Also, you should remove the ; after your if statements. They don’t hurt exactly, but they’re not doing anything and could cause confusion.