Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 Baalzamon · Mar 13, 2015 at 04:11 PM · unity 5unity5addcomponent

[solved] Load components via textfile config / AddComponent(string) with Unity5

I just upgraded from Unity 4.6.2f1 to Unity 5.0.0f4.

In my project I use a config file with names of components that should be loaded at runtime, via the gameObject.AddComponent(string) method.

Since Unity 5 this method is deprecated and the auto updater replaced it with a call to UnityEngineInternal.APIUpdaterRuntimeServices.AddComponent(...) which it tells me is not safe to use in the release build and I should use the generic Version of gameObject.AddComponent() or gameObject.AddComponent(Type) to add my components.

That's no option for me, as I want to load the components at runtime and I only know the name (string) of that component from the configuration file and not the specific type, but only that of the base class.

Anybody any idea how to fix that?

What I do is this: I have a base class, and inheret different subclasses to achieve different behaviours for different configurations, so you're able to switch behaviours by modifying the config file, without recompiling/building the whole project.

This is an example of how implemented a kind of strategy pattern, where the subclasses override abstract and virtual functions of the base class.

config file snippet

 <config 
   input_listener = "TestInput01"
 />

input listener base class

 using UnityEngine;
 using System.Collections;

 /* \class InputListener
  * 
  * Base class for all input listeners
  */
 public abstract class InputListener : MonoBehaviour 
 {
     public abstract ParseInput();
 }


input listener 01

 using UnityEngine;
 using System;
 using System.Collections;
 
 /* \class TestInput01
  * 
  * A simple input listener
  */
 public class TestInput01 : InputListener 
 {
     /* ParseInput() 
      * 
      * Evaluate keys pressed
      */
     public override void ParseInput() 
     {
         // do something when the escape key is pressed
         if (Input.GetKeyDown (KeyCode.Escape)) 
         {
             // do something ...
         }
     }
 }

input listener 02

 using UnityEngine;
 using System;
 using System.Collections;

 /* \class TestInput02
  * 
  * Another simple input listener that does something else
  */
 public class TestInput02: InputListener 
 {
     /* ParseInput() 
      * 
      * Evaluate keys pressed
      */
     public override void ParseInput() 
     {
         // do something else when the escape key is pressed
         if (Input.GetKeyDown (KeyCode.Escape)) 
         {
             // do something else
         }
     }
 }

game controller

 /* \class GameController
  */
 public class GameController : MonoBehaviour 
 {
     public const string APPLICATION_PATH = Application.dataPath;
     public const string RESOURCE_PATH = "/Resources/";
     public const string CONFIG_PATH = "Config/";
     public const string CONFIG_NAME = APPLICATION_PATH + RESOURCE_PATH + CONFIG_PATH + "configs.xml";

     // configuration files
     private XmlConfigs configList;
     private string configName;;
 
     // yadda yadda ...
 
      /* InitializeConfig()
      * 
      * Load components according to the specified config name in the configuration file
      * 
      * call the subclass input listeners method via GetCompenent<InputListener>().ParseInput()
      */
     private void InitializeConfig()
     {
         // load and deserialize XML config file
         configList = XmlSupport.DeserializeXml<XmlConfigs>(GameController.CONFIG_NAME);
         configName = configList.active;
         
         // find the specified config
         foreach (XmlConfig xmlConfig in configList.configs) 
         {
             // and add the component
             if (xmlConfig.name == configName)
             {
                 // that's how it worked for me in Unity 4.6.2
                 gameObject.AddComponent(xmlConfig.inputListener);
 
                 // that's what the autoupdater made of it, and it won't build
                 // UnityEngineInternal.APIUpdaterRuntimeServices.AddComponent(gameObject, "Assets/Resources/Scripts/Controller/GameController.cs (452,5)", xmlConfig.dropBehaviour);
                 break;
             }
         }
     }
 
 }
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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Glurth · Mar 13, 2015 at 06:58 PM

You can always look them up yourself. (something like this- uncompiled, may have typos)

 InputListener AddMyInputListenerComponent(string componentTypeName)
 {
    if(componentTypeName=="TestInput01")
       return gameObject.AddComponent<TestInput01>();
    if(componentTypeName=="TestInput02")
       return gameObject.AddComponent<TestInput02>();   
 }

You could make this function even more general, by returning a MonoBehavior, rather than an InputListener.

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 Baalzamon · Mar 14, 2015 at 01:35 PM 0
Share

Thank you, you're right. I could 'fix' it that way, and you couldn't know, but that's exacly what I did in the past. Sorry I should have been more sopecific. :)

I liked the 'magic' the AddCompoment(string) method provided and I'm sad that the feature is gone in the new release.

I tried several approaches (via Resources.Load etc.) but it always boils down to 'you can use it in the editor, but not in the release build'.

I'm curious... does somebody know what happened, that the feature got kicked out?

avatar image Bunny83 · Mar 20, 2015 at 05:41 AM 0
Share

The way GetComponent (and AddComponent) has done this in the past was actually looking up the type by name. To get a System.Type object for a class by a string you would simply use System.Type.GetType(). It returns the System.Type object for the given classname.

So even as a one-liner this should work:

 gameObject.AddComponent(System.Type.GetType("TestInput01"));


avatar image Glurth · Mar 21, 2015 at 01:43 PM 0
Share

@bunny83, that comment certainly seem like a better answer than $$anonymous$$e. Perhaps you should convert it to an answer?

avatar image Baalzamon · Mar 21, 2015 at 02:43 PM 0
Share

Thank you guys and sorry for beeing offline for a while.

bunny83, thanks for your comment, thats exactly what I was looking for! You should really convert that comment to an answer. :)

Glurth, the Dictionary approach has the same flaw as the lookup via switch/case or if/else. I have to populate it by hand, which the 'magic' of the previous AddComponent $$anonymous$$ethod took from me. But thanks anyway.

I was sure that I tried to add the component in the fashion bunny83 suggested, and that it didn't work for me in past. I wanted to repeat the error but this time it worked. Surely I must have done something wrong then, so thank you for letting me try again. ;)

avatar image Baalzamon · Mar 21, 2015 at 03:26 PM 0
Share

I just tried to find out what I was doing in the past and I'm pretty sure that I tried gameObject.AddComponent(("TestInput01").GetType()) which won't work and not gameObject.AddComponent(System.Type.GetType("TestInput01")) which works like a charm.

Thanks again.

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.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Unet NetworkServer.Spawn() not working 5 Answers

Does Unity UI System have a foldable field? 0 Answers

Scrip cannot work after reloading the scene or reopen Unity 0 Answers

Why an Android build doesnt make a _Data file. 1 Answer

Need to Include a file in the build and use it in the runtime 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