- Home /
How to find a Class by value
I am making a Card game and I have the scripts Player and Bot for the 4 gameobjects (3 Bots and 1 player) Bot of the two scripts have a public int x. What I want to do is sort the scripts by x and put them in a List/Array.
Thanks in Advance!
Answer by Kishotta · Sep 23, 2017 at 04:48 PM
You're probably looking for either an Interface or making the Player and Bot classes derive from a parent class (`Participant` or some such).
That sounds good, do you think you could explain that to me? I'm sorry I am very new to coding
No problem. A class can either derive from one parent class, or "implement" as many interfaces as you like.
Using the derived class suggestion from my previous comment would mean making a new class called "Participant" or whatever sounds good to you, and having both Bot and Player derive from it. If you have a list of Participant objects, you can add both Bot and Player objects to the list (Bots and Players ARE Participants). This is called polymorphism (for future Googling).
Going the Interface route, You would call it IParticipant or similar (for convention's sake). and having both Bot and Player implement that interface. Similarly to the above, you could make a list of IParticipant objects and fill it with Bots and Players. Implementing the interface means that the class is guaranteed to have the variables/methods that are present in the interface.
For this problem, both approaches are more-or-less identical, but Interfaces are primarily meant for having several very different classes share little bits of functionality (my go-to example being that you might want a Player, an ExplodingBarrel, and an NPC to all have a Die() method). Class inheritance is used to signify that two different classes are just specialized versions of the same thing with the same basic functionality (Pen and Pencil might both be WritingUtensils).
Sorry if that's too long winded or unhelpful!
No, that's great. Thank you very much! If I want to use an Interface, where would I code it?
Answer by Raimi · Sep 23, 2017 at 04:32 PM
You need to make a List of the scripts you need, then sort the list. Check out the link below, you may find your answer there...
https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object
$$anonymous$$y problem is that I have multiple different classes to search