Onsho Tang
Onsho Tang

Reputation: 1

Creating An empty gameobject, storing the data of an existing gameobject in the new gameobject and then destroying the existing gameobject

I want to store the existing data of a game object in a new game object (Without instantiating it until I want too) and then delete the existing game object thus giving me an exact clone (which is not instantiated in the scene)

So I stored the copy of the game object in a list as I want multiple of them that I can instantiate at any time. If I don't Destroy(ExisitngGameObject), a copy will be made however when I destroy existing game object the supposedly copied game object will be missing object in the List

`//#1
GameObject CloneObj;
CloneObj = ExistingObj;
CloneList.Add(CloneObj)
Destory(ExisitingObj);`

//2 
GameObject CloneObj = new gameobject();
CloneObj = ExistingObj;
CloneList.Add(CloneObj)
Destory(ExisitingObj);`

//#3
CloneObj = Instantiate(ExisitingObj);
CloneObj = ExistingObj;
CloneList.Add(CloneObj)
Destory(ExisitingObj);`

//#4
GameObject CloneObj= new GameObject();
CloneObj.name = ExisitingObj.name;
CloneObj.transform.position =ExisitingObj.transform.position;
CloneObj.transform.rotation = ExisitingObj.transform.rotation;
CloneObj.transform.localScale = ExisitingObj.transform.localScale;
CloneObj = ExistingObj;
CloneList.Add(CloneObj)
Destory(ExisitingObj);
`

Results:

1 - Missing Object in list when destroyed existing object

2 - creates an empty game object in scene

3 - creates an inactive game object clone in the scene which I do not want

4 - creates a clone which is in the scene with only transform values which I do not want.

I would only like to store a copy kof the existing game object and destroy it and instantiate the stored copy from the list in the future e.g press a button or something happens.

Upvotes: 0

Views: 1371

Answers (1)

zambari
zambari

Reputation: 5035

take your attempt 3 and skip line 2:

CloneObj = Instantiate(ExisitingObj);
//CloneObj = ExistingObj; //remove this line
CloneList.Add(CloneObj)
Destory(ExisitingObj);

First you make your instance, but then you replace a reference to your new instance with a reference to the original object, you add it to the list and destroy it. If I understand correctly you want to keep the reference to the new object but destroy the old one, so don't loose a reference to the new one

Upvotes: 1

Related Questions