• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by jmgek · Aug 25, 2015 at 08:47 PM · components

Dynamic AddComponent?

Hey guys, I am looking for a way to add components that I either store in a list or anywhere to attach them to gameobjects,

 foreach (string componentItem in listOfComponentsToAddToStartOfGame){
             GameObject gameObjectCheck = GameObject.Find(componentItem);
             if (gameObjectCheck == null){
                 gameObjectCheck = new GameObject(componentItem);
                ******* gameObjectCheck.AddComponent<componentItem >();
                //This is where I wanted to attach components...

Thanks,

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by cjdev · Aug 26, 2015 at 07:59 PM

You can do it but it's not pretty, you need to use the types and reflection like this:

     List<Type> componentList = new List<Type>();

     componentList.Add(typeof(Rigidbody));
     componentList.Add(typeof(Animator));

     GameObject go = new GameObject("MyGameObject");
     
     foreach(Type component in componentList)
     {
         var methodInfo = typeof(GameObject).GetMethods().Where(x => x.IsGenericMethod)
              .Where(x => x.Name == "AddComponent").Single();
         var addComponentRef = methodInfo.MakeGenericMethod(component);
         addComponentRef.Invoke(go, null);
     }
Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Scribe · Aug 26, 2015 at 08:12 PM 2
Share

why not just:

 List<System.Type> componentsToAdd;
 
 void Start(){
     componentsToAdd = new List<System.Type>();
     componentsToAdd.Add(typeof(BoxCollider));
     gameObject.AddComponent(componentsToAdd[0]);
 }

maybe with some error handling in case that last line is not actually adding a component! (see try and catch)

avatar image jmgek · Aug 26, 2015 at 08:15 PM 0
Share

This is awesome but I can't use where, it's throwing the system.array at me. I have not had that before.

avatar image cjdev · Aug 26, 2015 at 08:24 PM 2
Share

You'll need using System.Linq; for the Where part.

Edit: and @Scribe has a much better version anyways, I didn't realize that version of AddComponent had a generic overload.

avatar image Dave-Carlile · Aug 26, 2015 at 08:29 PM 2
Share

I'm not sure if the reflection functionality is completely cross platform, so that may be an issue for you. To rif on Scribe's comment a bit, you can expand it a bit to allow adding components by name...

 Dictionary<string, System.Type> components = new Dictionary<string, System.Type>();
 ...
 components.Add("Foo", typeof(Foo));
 components.Add("Bar", typeof(Bar));
 ...

 void AddComponentByName(string name)
 {
    System.Type componentType;
    if (components.TryGetValue(name, out componentType))
    {
      gameObject.AddComponent(componentType);
    }
 }
avatar image jmgek · Aug 26, 2015 at 08:40 PM 0
Share

Thanks so much guys!

avatar image
0

Answer by Dave-Carlile · Aug 25, 2015 at 09:40 PM

One of the AddComponent overloads takes a class name instead of a type. So just call it with the name of the class from your list.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image jmgek · Aug 25, 2015 at 09:45 PM 0
Share

That's what I am trying to do in 5 and it's not working.

 string componentItem = "Foo";
 gameObjectCheck.AddComponent<componentItem >();
 

Will not work...

avatar image Dave-Carlile · Aug 25, 2015 at 09:54 PM 0
Share

That's not the proper version of AddComponent. Use the first one that shows up in my link. You don't use the syntax. Just pass the component name...

 AddComponent("YourComponentName");

Or to use your code...

 string componentItem = "Foo";
 gameObjectCheck.AddComponent(componentItem);
avatar image jmgek · Aug 25, 2015 at 09:57 PM 0
Share

I should have added more info about the problem, but I cannot use that in 5.1 since AddComponent("String") has been removed. So I am wondering what I can do for generics now... alt text

test.png (8.3 kB)
avatar image
0

Answer by _Gkxd · Aug 26, 2015 at 07:38 PM

Instead of storing the names of the classes, you can just store the list of components:

Include this line at the top of your script

 using System.Collections.Generic;

Somewhere inside the class

 List<Component> componentsToAdd; // Your list of components

 void Start() {
     componentsToAdd = new List<Component>();
     componentsToAdd.add(/* some component */); // Repeat as necessary
 }

When you want to add components

 foreach (Component c in componentsToAdd) {
     someGameObject.AddComponent(c.GetType());
 }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image jmgek · Aug 26, 2015 at 07:49 PM 0
Share

How would I be able to add a component to the list?

  componentsToAdd.Add(typeof(Game$$anonymous$$anager));

is not working. Thanks,

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

28 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to add a component to all selected objects? 1 Answer

Import assets, linking their components automaticly. 0 Answers

Destroying Components from Editor Script Throwing MissingReferenceException 1 Answer

Model - get mesh component 0 Answers

Character controller not fitting through door 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges