- Home /
scripts as a addcomponent to a gameobject
Hi,
I've read the reference to AddComponent but its not making sense and when using the mono editor, its still not making sense.
here's where i am stuck at:
Apple A=new Apple;
A.setName("Green Apple");
GameObject Bob=(GameObject) Instantiate(Resources.Load("Bob"),Vector3.zero,Quaternion.identity);
how do I attach 'A' to Bob?
would:
Bob.AddComponent() <-- wouldnt this just attach a new script component to bob and not the one create 'A' above?
Bob.AddComponent("Apple") <--- isnt this the same as above , adding a new component of script Apple to Bob.
i m trying to figure out how to attach the already create 'A' to Bob.
Thanks
Only way i can think of would be to add the script component first and then configure it afterward.
or add another add functions inside the script to return the private members and reassign to the BOB gameobject.
Answer by ncallaway · Jan 05, 2014 at 08:09 AM
I'm not sure of a way of precreating the Component and adding it to a specific object. You can use AddComponent to create a new component object, and then set the properties on it that you want.
GameObject Bob=(GameObject) Instantiate(Resources.Load("Bob"),Vector3.zero,Quaternion.identity);
Apple apple = Bob.AddComponet<Apple>();
apple.setName("Green Apple");
As an post-script, I generally recommend using the generic version of AddComponent rather than the version that takes a string. It makes your code more type-safe, and makes it easier on the tooling if you want to later rename the "Apple" class to something else (maybe it becomes the Fruit class instead of the Apple class).
For more information check out http://docs.unity3d.com/Documentation/Manual/GenericFunctions.html and http://msdn.microsoft.com/en-us/library/512aeb7t.aspx
Thanks, I was hoping for a way to add the already created component and then assigning it as as the component is going to be configure during a routine, the code will just change so that the component is already added to the object.. also thanks for teh suggestion to use type rather than string.
Answer by DTek · Mar 28, 2015 at 11:11 AM
If you need to keep track of certain content within the Component then use it later for the recently created game object, simply create a new component for the object and transfer the variables from the old component to the newly created one.
Your answer

Follow this Question
Related Questions
Script Component unchecks itself prior to build. 1 Answer
Object reference not set to instance of an object 2 Answers
Detect collision when changing character controller height 2 Answers
Delete a script component if object has already one 2 Answers
How do I replace a component with 'sent' component? Is this even possible in Unity? 1 Answer