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 kaitou · Jan 26, 2013 at 09:19 PM · c#arraylistsort

Sort an ArrayList of game objects by another script variable

So here the trick im trying to do, I am building a RPG-type game, And i have all the battle characters stored in a list. I want to sort this list so that the character with the highest turn speed(TSpeed number is at the top of the list(for simplicity's sake) to designate turns. Problem: How do i sort the ArrayList by the variable that is stored in another script? Here is the script that contains the Arraylist

 using UnityEngine;
 using System.Collections;
 
 public class BattleSystem : MonoBehaviour {
     
     GameObject[] Enemies;
     GameObject[] Players;
     ArrayList Combatants = new ArrayList();
     float starttimer, currenttimer;
     bool isPlayer= false;
     int curCombatantIndex;
     GameObject curCombatantObj;
     
 
     // Use this for initialization
     void Start () {
         Enemies = GameObject.FindGameObjectsWithTag("Enemy");
         Players = GameObject.FindGameObjectsWithTag("Player");        
         foreach ( GameObject enemy in Enemies)
         {
             
             Combatants.Add(enemy);
             
         }
         foreach ( GameObject player in Players)
         {
             
             Combatants.Add(player);
             
         }
         enter code here

For the sake of refences, all of the charcters have the same script attached to them that holds their stats. Heres that script: using UnityEngine; using System.Collections;

 public class PlayerStats : MonoBehaviour {
     
     public float Health= 10.0f; 
     public float TSpeed= 10.0f;
     public float AP= 10.0f;
     public float PhysDef= 10.0f;
     public float MagDef= 10.0f;
     public float PhysATK= 10.0f;
     public float MagATK= 10.0f;
     public float PAL= 10.0f;
     public float EXP= 10.0f;
 
 }

I have heard of the IComparer function, but i can't really find anything that helps me out so far. Any help is appreciated Also, keep it C# pls

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

2 Replies

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

Answer by FL · Jan 27, 2013 at 12:53 AM

I use the second code in item 2 of http://docs.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html . Use

 Array.Sort(putYouArrayHere,(IComparer)new sortPlayerStatsSpeed());

Put in your BattleSystem class:

   private class sortPlayerStatsSpeed: IComparer{
      int IComparer.Compare(object a, object b){
         PlayerStats p1=((GameObject)a).GetComponent<OtherScript>();
         PlayerStats p2=((GameObject)a).GetComponent<OtherScript>();
         if (p1.TSpeed > p2.TSpeed)
           return 1;
         else if (p1.TSpeed < p2.TSpeed)
           return -1;
         else
           return 0;
      }
   }
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 kaitou · Jan 27, 2013 at 04:04 AM 0
Share

Thank you so much! I made two edits of this so for the reference you have it

  PlayerStats p1=((GameObject)a).GetComponent<OtherScript>();
 PlayerStats p2=((GameObject)b).GetComponent<OtherScript>();



and i used hits call

 Combatants.Sort((IComparer)new sortPlayerStatsSpeed());


the other threw an error at me. XD

avatar image FL · Jan 27, 2013 at 12:30 PM 0
Share

Try: Array.Sort(Combatants,(IComparer)new sortPlayerStatsSpeed());

avatar image
0

Answer by mstultz · Jan 27, 2013 at 04:25 AM

You know, instead of using an ArrayList, you could use a List< PlayerStats > and then use System.Linq to sort by specific attributes (via OrderBy or OrderByDescending). For example you could change the commented lines of your original question:

 //ArrayList Combatants = new ArrayList();   becomes:
 List< PlayerStats > Combatants = new List< PlayerStats >();
 
 // Then...
 //Combatants.Add(enemy);  becomes:
 Combatants.Add( enemy.GetComponent< PlayerStats >() );
 
 //Combatants.Add(player);  becomes:
 Combatants.Add( player.GetComponent< PlayerStats >() );
 
 // Finally...
 var sortedCombatantsAscending = Combatants.OrderBy( x => x.TSpeed ); // for 1, 2, 3
 var sortedCombatantsDescending = Combatants.OrderByDescending( x => x.TSpeed ); // for 3, 2, 1
 
 
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 kaitou · Jan 27, 2013 at 04:45 PM 0
Share

I thought this functionality was in Java only, not C#?

avatar image mstultz · Jan 28, 2013 at 02:24 AM 0
Share

I'm not sure about Java, but it definitely works for C#; I tested out the sorting code before submitting my answer. Just be sure to include the 'using System.Linq;' statement.

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

11 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

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Distribute terrain in zones 3 Answers

Multiple Cars not working 1 Answer

Getting data from Arraylist within Arraylist 0 Answers

Is it possible to sort an array determined by an external comparison? 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