- Home /
How to duplicate a GameObject?
This is not a duplicate! Why? Because I've tried different variants of Instantiate() with gameObjectToCopy and its transform as parameteres and none did the trick. What I want is exactly the same object (the same size, position, rotation, material, everything) but, of course, a copy, not a reference. But when I use Instantiate() the result is weird - the cloned object is scaled down/missing its material/whatever. So how to duplicate a GameObject to get the exact copy (in script)?
Example code:
copy = ((Transform)Instantiate(piece.transform, piece.transform.position, piece.transform.rotation)).gameObject;
copy = (GameObject)GameObject.Instantiate(piece);
Can you show some code of one of your attempts? I've used Instantiate and it seems to work fine.
Instantiate() is the right way. Is this a prefab? Are you making material/scale changes in scripts? Are you using a "real" prefab or are you using a scene object? As @whebert asks, can you show us some code?
I've never had this trouble with a "normal" game object. Instantiate() always produces a perfect copy. I've read some posts where people have had scale issues with object containing animations. Can you duplicate this issue using the same material changes on built-in primitives? What material changes are you making?
Everything that has the same material at the start of your app will share that material. Any material change at runtime will result in that shared material being duplicated and the object getting its own unique material instance. This includes shader changes. This doesn't explain why you are having problems with Instantiate(), but just wanted to point out that even a small change may have a large impact on your object's environment.
I've never had this problem, and I did some searches and came up empty for other people having this problem. So whatever it is, it is likely rare (and may not be an Instantiate() issue at all). Could it be a mesh issue? That is, if you replace the mesh you use without another authored in a different environment does the problem still occur? Are you making the object a child of another object?
Without more information or a cut down version of the project to play with (or someone who has had this specific problem reading your question), all the list can give you is guesses.
Answer by TheCreeperMiner · Mar 29, 2015 at 06:28 PM
g00d Try to select object and then click CTRL + D... :D
Answer by CyberBlack · Mar 16, 2013 at 02:46 PM
Try to select object and then click CTRL + D...
I liked Try to select object and then click CTRL + D... Because I'm not good in scripting, better I'm begginer in unity