• 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 /
  • Help Room /
This question was closed Apr 07, 2018 at 03:09 PM by meat5000 for the following reason:

The question is answered, right answer was accepted

avatar image
1
Question by Antoids · Apr 07, 2018 at 06:57 AM · scripting problemvariablesgameobjectsaddcomponent

Add a script to a GameObject via script at runtime?

I have a number of prefabs that are not very different aside from the scripts attached to them. I was wondering if there was a way to use AddComponent or something similar to add scripts to a newly-Instatiated GameObject using a variable to identify the script. I couldn't find this in the documentation and experimented with strings named after the script or feeding a script into the function unsuccessfully.

So, in brief, what I'm looking for is something like:

 void CreateObjectWithScript(string scriptName){
 GameObject go = (GameObject)Instantiate(new GameObject, new Vector3(), Quaternion.identity);
 go.AddComponent<scriptName>();
 }

This way, rather than creating a script and a prefab for each such object, I can just create one generic prefab and attach scripts to them at runtime, deriving any changes needed out of the script.

However, the above code gives me the error: "'scriptName' is a variable but is used like a type"

I tried also using "go.AddComponent(scriptName.GetType());" , but in implementation, naming a script would give the error: "'ScriptToBeAdded' is a type, which is not valid in the given context."

Following that, I have also attempted:

     private void Start() {
         CreateObjectWithScript(ScriptToBeAdded);
     }
 
     void CreateObjectWithScript (Type type){
          GameObject go = (GameObject)Instantiate(new GameObject(), new Vector3(), Quaternion.identity);
          go.AddComponent(type);
      }

This gave the same "'ScriptToBeAdded' is a type, which is not valid in the given context." error as before.

Comment
Add comment · Show 3
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 toddisarockstar · Apr 07, 2018 at 07:41 AM 0
Share

what is the error you are getting? your script example looks correct

Show more comments

1 Reply

  • Sort: 
avatar image
0
Best Answer

Answer by Antoids · Apr 07, 2018 at 08:52 AM

Solved it myself after messing with it for a bit. The following code will achieve the desired effect:

 public GameObject prefab;
 
     private void Start() {
         CreateObjectWithScript(prefab, typeof(ScriptToBeAdded));
     }
 
     void CreateObjectWithScript (GameObject prefabName, Type type){
          GameObject go = (GameObject)Instantiate(prefabName, new Vector3(), Quaternion.identity);
          go.AddComponent(type);
      }
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 TreyH · Apr 07, 2018 at 02:30 PM 0
Share

There's a more natural way to pass Type arguments to functions, btw:

 void CreateObjectWithScript<T> (GameObject prefabName){
     GameObject go = (GameObject)Instantiate(prefabName, new Vector3(), Quaternion.identity);
     go.AddComponent<T>();
  }

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

140 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 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 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 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 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

Changing a variable from another script 1 Answer

Display Variable with UI Text 2 Answers

Invoking a Function From A Variblized Script And Object 1 Answer

Identifying 3 GameObjects in contact with each other,Identifying and destroying 3 Game Objects with the same LayerName 0 Answers

How can I reference a script in a specific gameobject if that same script exists in other gameobjects? 1 Answer


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