var isplaceobject;
function spawn()
{
isplaceobject = 1;
while(...)
{
... // other code
You also need to move the "wait(1);" outside the if-branching, as it will otherwise produce a crash if the trace hits nothing or hits an object from the inside.
I don't know why you're getting more than 1 cubes, maybe you're calling the function more than once at the same time?
Also add a break; or return; here:
if(ghostobject != NULL)
{
ent_remove(ghostobject);
isplaceobject = 0;
return;
}