Duplicated Object components still a reference

I’m using this snippet to duplicate a GameObject:

GameObject newObj = (GameObject) Instantiate(GameObject.Find(name));
newObj.name = "NewThing";
Vector3 newPosition = new Vector3(newObj.transform.position.x - 1.0f, newObj.transform.position.y + 1.2f, newObj.transform.position.z + 2.2f);
newObj.transform.position = newPosition;

The object is created and moved but certain components are still linked together, most importantly, the mainTexture. How can I copy an Object and make sure that each component is also a new copy?

According to the docs, “If the object is a Component or a GameObject then entire game object including all components will be cloned.” This doesn’t seem to be happening…

Some things are shared. For example the material and the mesh are shared. Other things are not. Can you give us a specific example of the behavior you are having trouble with? What is the clone actually doing, and what do you want it to do.

Well, in this case I want to be able to manage the colors of the mainTexture independently, that's how I noticed. I have a fairly simple method that gets the pixels of the mainTexture, and changes all instances of one color to another. When done on one the original object, the same changed happened on the clone... I don't want that to happen.

2 Answers

2

The material will be different, so you could change the color on that material (depending on shader, will tint your texture). Otherwise, use the Texture2D routines to make a new one, Get pixels from original, Set/Apply to the new one: http://docs.unity3d.com/Documentation/ScriptReference/Texture2D.Texture2D.html

I was just editing my last comment on the original post, but I’ll drop it down here instead. Since Instantiate should work on any object… I added this:
Texture newTexture = (Texture) Instantiate(renderer.material.mainTexture);
newObj.renderer.material.mainTexture = newTexture;

Worked just fine :slight_smile:

Converted to answer