Destroying/Parenting Troubles

Hey everyone. I have been trying to figure out the problems of this script for quite some time now, so I thought some of you may be able to help me. What I am trying to do is spawn a prefab to be a child of a gameobject which already exists. I then want to be able to swap that prefab with another when you press a GUI button.

This is my attempt.

var shape1 : GameObject;
var shape2 : GameObject;
var wantedshape : GameObject;
var currentshape : GameObject;

function Start () {
currentshape= shape1;
 Instantiate(currentshape, transform.position, transform.rotation);
}

function OnGUI () {


	GUI.Box (Rect (10,10,100,90), "Custom Shape");


	if (GUI.Button (Rect (20,40,80,20), "Shape1")) {
	    Destroy(currentshape);
		wantedshape = shape1;
		Instantiate(wantedshape, transform.position, transform.rotation);
		currentshape = wantedshape;
		currentshape.parent = transform;
		
		
	}
	}

At the moment it will not let me destroy the existing prefab, because “Destroying assets is not permitted to avoid data loss.” It also appears I do not understand how to make the new prefabs childs of the game object properly.

Any help would be great… Thanks

anyone? -_-

Hi, im not sure but looks like you are destroying “shape 1” and calling it again.

function Start () { 
currentshape= shape1;

here you assigned shape 1 to currentshape

 Destroy(currentshape); 
      wantedshape = shape1;

here you destroyed currentshape wich is shape 1
so shape 1 is destroyed.
and wantedshape calls shape 1 wich has been destroyed and its not in the sene anymore.

Didn’t you mean to put "wantedshape = shape 2??

anyhow the code look like hmm wierd hehe

Yes I did :stuck_out_tongue: I fix it thanks lol.

var shape1 : GameObject;
var shape2 : GameObject;
var wantedshape : GameObject;
var currentshape : GameObject;

function Start () {
wantedshape= shape1;
currentshape = Instantiate(wantedshape, transform.position, transform.rotation);
}

function OnGUI () {


   GUI.Box (Rect (10,10,100,90), "Custom Shape");


   if (GUI.Button (Rect (20,40,80,20), "Shape1")) {
       Destroy(currentshape);
      wantedshape = shape1;
      currentshape = Instantiate(wantedshape, transform.position, transform.rotation);
     
      
      
   }
   }

now I just have to parent it

Ok I have solved the parenting issue now too, with

currentshape.transform.parent = coreObject.transform;

where coreObject is the empty game object. Its amazing what a good night sleep can do to your brain that lets you solve syntax.