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
1
Question by PsychoDuckArcade · Nov 26, 2014 at 12:20 PM · typesyntaxgeneric

Passing Type variable to generic type: Variable not found.

I'm just trying to pass a type to a generic method, but it's giving me a syntax error; Error 1 The type or namespace name 'type' could not be found (are you missing a using directive or an assembly reference?)

 for (int i = 0; i < Loadout.Count; i++)
         {
             for (int n = 0; n < Loadout.ElementAt(i).Value.Count(); i++)
             {
                 Type type = Loadout.ElementAt(i).Key;
                 Game.Manager.SpawnItem(Detach<type>(i, gameObject), transform.position);
             }
         }


It's referring to my Type variable (type) in the Detach generic method. It can't find type even though it's declared and initialized right above it.

And the dictionary DOES use Type for it's key:

 public Dictionary<Type, Item[]> Loadout = new Dictionary<Type, Item[]>();

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
3
Best Answer

Answer by Immanuel-Scholz · Nov 26, 2014 at 12:46 PM

You cannot pass a variable of Type "System.Type" as a generic parameter to a generic function directly.

The reason is: Generic parameter are replaced when the code is compiled. Variables store values when the code executes.

One solution is to replace the generic function with a non-generic that accepts the type as a normal parameter

 void Detach(Type t, int i, GameObject go) {
     ...
 }

This works, if you only use the generic parameter in a "typeof(T)" - statment, but if you use the generic parameter in another generic way (e.g. Dictionary) then you would have to replace that call again (e.g. with "Hashtable")..

If you are not afraid of C# internas and dynamic type generation and if you are not deploying on iOS (because that does not support dynamic code generation at all), then you can compile the correct call to Detach at runtime. Remember that this is significant slower than any "non-generic code with lots of casts".

 MethodInfo genericFunction = GetType().GetMethod("Detach");
 MethodInfo realFunction = genericFunction.MakeGenericMethod(Loadout.ElementAt(i).Key);
 var ret = (GameObject)realFunction.Invoke(this, new object[]{ i, gameObject });
 Game.Manager.SpawnItem(ret, transform.position);
 

This code assumes that "Detach" is public and declared in the same class as the code above is. And the parameter of Detach are exactly "int" and "GameObject" and the return type is "GameObject".

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 PsychoDuckArcade · Nov 26, 2014 at 01:13 PM 0
Share

Thanks I used that first solution for performance. I made the type parameter in Detach a generic in the first place so that I can return that type at the end of the function. Now it just returns a base class type so I have to cast it:

 Weapon myWep = (Weapon)Detach(typeof(Weapon), 0, gameObject);

Also I now have to surround the type parameter with typeof() every time.

$$anonymous$$inor inconveniences but it seems to work perfectly now so I guess I'll live with it. Thanks.

avatar image Bunny83 · Nov 26, 2014 at 01:35 PM 2
Share

@Chris_Devl: The usual solution for this is to use a generic overload, the same way Unity does for GetComponent. GetComponent actually takes a System.Type parameter but they implemented a generic version like this:

 public T GetComponent<T>() where T : Component
 {
     return GetComponent(typeof(T)) as T;
 }

That way you can use the generic version when using it manually in code and the System.Type version when you work with variables.

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

27 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

Related Questions

Syntax for method wich returns generic type (own class)? 0 Answers

C# Generic return type 1 Answer

get component type at runtime using generic GetComponent in C# 1 Answer

Boo help: method not defined 4 Answers

what is the correct syntax for the creation of arrays? 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