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

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 Generic classes and methods | Microsoft Learn

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.