Adding components to gameobject programmatically

I know that you can add a component to a game object using AddComponent, and add a component by type. Can you add an ‘instance’ of a component to a game object?

Instead of:

myGameObject.AddComponent(typeof(MyType))

can you do something to the effect of:

MyType t = new MyType;
t.myParam = 1;
etc…

myGameObject.AddComponent(t);

Thanks.

No, you cannot.

Theoretically, there should be an easy workaround for this, but it’s broken. This would only work in the Editor, though.

http://answers.unity3d.com/questions/1114/what-is-editorutility-copyserialized-supposed-to-do

As it is, what you want to do can surely be done, but it’s a freakin’ pain.

http://forum.unity3d.com/viewtopic.php?p=238473

Thanks for the replies. I’ll just go the route of adding components and post-modifying, it definitely is a harder road the other way.

I appreciate the info!

MyType t = gameObject.AddComponent( typeof(MyType) ) as MyType;
t.myParam = 1;

Yeah, that’s the pain that I mentioned. Not a lot of fun when you’re not just using one property.