Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 MasterChameleonGames · May 23, 2019 at 10:54 PM · generics

Constrain Generic to Specific Classes

If I have a function

 T Function <T> (T script) where T: ??? { }

How do I constrain T to specific classes, such as accepting SpriteRenderers and Images?

I'm probably misunderstanding generics, is there another way to constrain a parameter of a function to multiple classes?

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

Answer by mchts · May 24, 2019 at 01:23 PM

You could do sth like :

 T Function<T, U, V>(T script) where T : V, U { } 

but T should have been derived from U and V... so this couldn't be considered as useful. There is a more straightforward way of doing what you want. And it's overloading method as you need:

 SpriteRenderer Function (SpriteRenderer script){ }
 Image Function (Image script){ }

etc.

Comment
Add comment · Show 8 · 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 MasterChameleonGames · May 24, 2019 at 06:50 PM 0
Share

I don't really get the first one, but you said it won't help, so I guess it doesn't really matter.

I could do the second one, but there'll have to be different names for each one, so...

Also, I came up with an idea, but I have no idea if it would work:

  T Function <T> (T script) {
     if(typeof(script) == SpriteRenderer) {
         SpriteRenderer script = script as SpriteRenderer;
     }
     else print("Not acceptable type");
  }
avatar image mchts MasterChameleonGames · May 24, 2019 at 09:07 PM 0
Share

It will work with a little workaround:

 T Function <T> (T script) {
      if(typeof(T) == typeof(SpriteRenderer)) {
          SpriteRenderer script = script as SpriteRenderer;
      }
      else print("Not acceptable type");
   }

but it is not best practice. When it comes to the second solution your function name won't change but you will have multiple options with same method name and you will also able to restrict the types you want to use. Do not hesitate using overload methods. But again you could go with your approach.

And when it comes to @ShadyProductions 's solution it will also work but your method will accept any type that derives from Component base class. You could use this approach too unless you want to restrict your types with specific ones.

avatar image MasterChameleonGames mchts · May 24, 2019 at 09:21 PM 0
Share

Oh never$$anonymous$$d, I misinterpreted overloading methods, I thought the return type has to be different, not the parameters.

The second method would work then, thank you.

Show more comments
avatar image
1

Answer by Bunny83 · May 24, 2019 at 11:00 PM

Generics are a bit tricky. You can use any type as constraint. However the types allowed would be the class specified in the constraint or any derived class. Note that multiple generic constraints are not combined with "or" but with "and". So all constraints you put on a type parameter have to be fulfilled at the same time. So it's not possible to specify two different types as constraints since a a type can't be a SpriteRenderer and MeshRenderer at the same time.


Note that generics are fully compiled at compiletime. So the code inside a generic method need to work with all types you are allowed to pass in as type parameter. A generic method without any constraints can't do much since there's almost no common ground. By applying constraints to the type parameter you essentially set up a "contract" so the compiler knows whatever type will be used will have these specifed things. The actual type binding is done dynamically at runtime. That's why the code need to compile with all acceptable types.


Your usecase isn't quite clear. If you just want to prevent a method from being fed a wrong type this can only be done with runtime checks unless the types you want to use have a a common basclass

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 MasterChameleonGames · May 24, 2019 at 11:45 PM 0
Share

So is using generics not really suitable for this?

I'm making a function that changes the color value of a component script, and Image, Text, SpriteRenderer, etc. all have a color variable.

avatar image Bunny83 MasterChameleonGames · May 25, 2019 at 08:14 AM 0
Share

Exactly, generics aren't suitable for this since just having a equally named property doesn't make the components related in the sense of OOP or inheritance. If two or classes do not have a base class or interface in common you can't treat them in a generic or abstracted way since there's no abstraction.

avatar image
0

Answer by ShadyProductions · May 24, 2019 at 06:58 PM

You can restrict T to a base class of a given type.

I believe most have Component as base class you could do where T : Component

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 MasterChameleonGames · May 24, 2019 at 07:06 PM 0
Share

Ok, thank you. Is there any way to go even more specific with that?

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

108 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

Related Questions

MonoBehaviour pseudo-singleton with C# generics 1 Answer

2 problems with serialization of a generic list of a custom class 3 Answers

(analytics beta) How to initialize Generic Dictionary from JS? 1 Answer

Big problem with a small singleton 1 Answer

Is the class derived/inherited from generic list serializable? 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