• 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
1
Question by actraiser3 · Jun 09, 2015 at 07:22 PM · c#casting

Casting to a Type using a String

Hello, I simply want to fetch a component from a gameobject and cast it using the AS-operator to the proper type. I do know the name of the type on runtime only and that name is stored in a string.

Using the type directly in code works fine:

 go.GetComponent(configuration) as Config1; // works 

But as I pointed out, I don't know about the type before runtime. All I have is a string and obviously this does not work:

 go.GetComponent(configuration) as "Config1"; // can not work

I tried to use getType to convert the string to the correct type like so:

 go.GetComponent(configuration) as Type.GetType("Config1"); // compile error

That results in the following error in Unity Editor: Unexpected symbol `(' (but no Error in MonoDevelop)

So, how do I convert the String "Config1" to a valid casting information?

Greets

Comment
Add comment · Show 5
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 Dave-Carlile · Jun 09, 2015 at 07:30 PM 2
Share

What do you plan on doing with the value after you've cast it to an unknown type? Unless all of your unknown types have a common interface you won't be able to call methods on it, so the type cast isn't giving you anything. If they have a common interface then you can just cast it to the interface, or to the ancestor class, and call virtual methods.

avatar image tanoshimi · Jun 09, 2015 at 09:17 PM 0
Share

. +1 agree with @Dave Carlile. Similar to using eval() in JavaScript, or using dynamic SQL statements, patterns like this are typically a symptom of an incorrect design decision somewhere...

avatar image actraiser3 · Jun 10, 2015 at 06:23 AM 0
Share

Thanks for the suggestions. $$anonymous$$aybe it's just me diving into C# just recently and it's a matter of how to address inheritance correctly. Let me explain a little more in detail what I try to achieve.

$$anonymous$$y project will be compiled to different platforms in different versions (think paid and free version). For each build of the game there are little things to be differently configured. Depending on platform/version features need to be disabled, others need to be activated in different manners, e.g. Gamecenter on iOS only.

Now I thought it would be clever to check platform/version in the first scene and then attach one of a few different scripts with all configuration-information to be used throughout the game. That configuration-class inherits from an abstract Singleton BaseConfiguration.cs and is attached to a GameObject in the Scene tagged "Configuration".

Now, those files/classes are named like "ConfigAppleAppstorePaid.cs", "ConfigGooglePlaystoreFree.cs", etc and of course share fields and method names from the abstract BaseConfiguration.cs.

I do know the name of the script to be a attached to the "Configuration"-GameObject from my evaluation on game-start and I know it inherits from BaseConfiguration.cs. However I have trouble to achieve the goal to fetch that configuration from the GameObject again and cast it properly as all I have is the name of the class as string at that point.

I am sure there is some way to use the BaseConfiguration-Type as Casting-Target but I tried different variations and did not succeed. So maybe it's the syntax or maybe the idea how to solve my problem is not a clever one in the first place.

avatar image Ricewind1 · Jun 10, 2015 at 07:44 AM 0
Share

Unless you are going to make 2 separate versions of the game (one free, limited and one paid, full version) It's not going to work the way you want. Tricking the game into thinking it's the full version isn't that difficult for some people.

avatar image actraiser3 · Jun 10, 2015 at 08:11 AM 0
Share

Security as in preventing piracy is not my concern in this case. If it was, your point would be valid of course.

2 Replies

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

Answer by Dave-Carlile · Jun 10, 2015 at 11:33 AM

Use GetComponent < YourBaseType >(). Create a virtual method(s) in the base type that can do the config specific handling, override those methods in the child classes. Always use the virtual methods to do platform specific things depending on the config object instance.

Regardless, at some point in your code you'll need specific code to handle the specific differences such as different config screens, different code paths.

Another option for that sort of thing is to use conditional compilation, which might be better for your needs.

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 actraiser3 · Jun 10, 2015 at 12:00 PM 0
Share

Excellent - thank you, that did the trick for me. It was just a matter of using GetComponent with the right BaseType. Thanks again!

avatar image
0

Answer by dubbreak · Jun 09, 2015 at 08:29 PM

You need to look up reflection. Convert.ChangeType() in specific.

The problem with using reflection in Unity is it isn't supported by all platforms (to the best of my knowledge).

If it's just a case of proper subtyping and you don't have many types, you could cheat and use a switch statement (switch on the string and in each case do a normal cast).

Dave has a good point. What you are trying to do may not be necessary. Why do you think you need to cast? It might not be the best solution for the problem you are trying to solve.

Comment
Add comment · Show 2 · 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 actraiser3 · Jun 10, 2015 at 06:33 AM 0
Share

I have elaborated in the first answer a little more in detail what I try to achieve. But yes, a switch would work though it is not very elegant in code. But nevertheless thank you for that suggestion. Unless I change my whole approach because it is not clever, that is probably the way to go.

avatar image Dave-Carlile · Jun 10, 2015 at 11:28 AM 0
Share

I believe ChangeType only allows converting between CLR types such as int, single, string, etc.

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

6 People are following this question.

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

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer

Casting a GraphView node using GetNodeByGuid() returns null 1 Answer

Issue casting using Type variable? C# 2 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