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
0
Question by donimation · Sep 23, 2016 at 03:55 PM · arraylistleaderboardscoreboardarrange

store/rearrange integers for a basic scoreboard with C#

Hello everyone,

I'm programming my fist game and I'd like to learn how to create a scoreboard with C#. For now I'd be happy to have just the local/personal top 3 working, but eventually I'd like to see a board with the top 100 players online.

Basic if statements and simple methods have managed to get me surprisingly far, but for something like this I gather that I ought to look into Arrays or possibly even Lists.

The closest example that I've been able to find so far has been in this post here, specifically

  int [] highScore = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  
  int InsertScore( int score ) {
     int i = 0;
     //Look for the index to insert score
     while( i < highScore.length ) {
        if( highScore[i] <= score ) {
           break;
        }
        i++;
     }
     //Score doesn't make it to top 10
     if( i >= highScore.length ) {
        return -1;
     }
     //Push all the scores not higher than score backward
     for( int j = highScore.length - 1; j <= i; --j ) {
        highScore[j] = highScore[j-1];
     } 
     //Set score
     highScore[i] = score;
     return i;
  }

Thank you @Chronos-L

I can follow this enough to start implementing something similar in my own code but before attempting this I did a bit more research and read that "Arrays are outdated and Lists are the way to go" so to speak. I have a feeling that Lists might be slightly more flexible when it comes to arranging data partly because they don't have to have a fixed length.

Would Lists be able to handle this task in a more elegant way, and if so how? Since I'm still struggling with syntax any links or examples you can provide on the subject would be enormously appreciated!

Thank you for taking the time to read this and I look forward to any feedback!

Best regards, Don

Comment
Add comment · Show 1
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 EvilTak · Sep 23, 2016 at 04:52 PM 0
Share

Since you only need the top X scores, you don't need to resize your storage structure. Arrays will work out fine with the insertion method you use. This will overwrite the scores, however, which will lead to the 101th and above score being deleted. If you want to store all scores, use a file storage mechanism and retrieve only the top 100 scores each time the leaderboard is displayed.

2 Replies

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

Answer by donimation · Sep 30, 2016 at 03:32 PM

Ok, this is my solution:

 using UnityEngine;
 using System.Collections.Generic;              // TO ENABLE THE USE OF List<>
 
 public class YoClass: MonoBehaviour
 {    public static List<int> top3list;
         public static bool sortingStopped;      // STOPS THE LOOP 
 
         void Start ()
         {    top3list = new List<int>();
         top3list.Add(0);                      // QUICK AND DIRTY WAY TO CREATE
         top3list.Add(0);                      // 3 EMPTY "SLOTS"
         top3list.Add(0);
         sortingStopped  = false;
          }
     
      void Update()
      {    SortTheList(YoGame.currentScore);
      } 
 
      void SortTheList(int score)
     {    if (sortingStopped == false)
         {    if (score > top3list[2])
             {    top3list[2] = score;
                 top3list.Sort();
                 top3list.Reverse();
             }
             sortingStopped = true; 
         }
     }
 }


sorry for the weird formatting; had some troubles with dat:|

Might not be pretty, but it gets the job done.
Thanks again @Happy-Zomby!
Only thing I did different was to always re-assign the last index in order to keep the List count to 3.
Then I .Reverse(d) after .Sort(ing) to keep the top score at [0]

Hope this helps anyone else looking for a "basic" score board with C#, and if you think of a more efficient way to do the same thing feel free to post your solution!

Comment
Add comment · 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
1

Answer by Happy-Zomby · Sep 23, 2016 at 05:54 PM

hi, what you have should work but it is true that list would be easier... and it has functions to sort it and so on..... and you don't need to specify size

 using UnityEngine;
 using System.Collections.Generic;
 
 public class ScoreManager : MonoBehaviour {
 
     public List<int> scores = new List<int>();
     public bool test;
     public bool test2;
 
 
     public void AddScore(int score)
     {
         scores.Add(score);
         //will add your last score if you call it from somewhere else
     }
 
     public void SortScore()
     {
         scores.Sort();
     }
 
     void Update()
     {
         if(test==true)
         {
             test = false;
             AddScore(Random.Range(0, 1000));
         }
 
         if(test2 == true)
         {
             test2 = false;
             foreach (int sc in scores)
             {
                 Debug.Log(sc); 
             }
 
             SortScore();
 
             foreach (int sc2 in scores)
             {
                 Debug.Log(sc2);
             }
         }
 
     }


the update part is just so you can test it.... hit test a few times and then test 2 you will get the unsorted scores in the console - followed by the sorted ones.

so if you ignore the update part you see the power of list... 3 lines only: declare add sort and there you are

You can do even more advanced stuff with list using System.Linq but no need here. Lists are great - would recommend using them,

if you want to have a name with your score... you can great a class with a string and int... then make a list of that... and use OrderBy to sort the list of name/score by score... but this is more advanced... look for OrderBy for system.Linq for this

hope that helps

Comment
Add comment · Show 4 · 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 donimation · Sep 29, 2016 at 06:10 PM 0
Share

Thank you for the feed back @evil-tak and @Happy-Zomby thank you for that last bit of advice on a class with name/score info in it for online leaderboards; I will keep that in $$anonymous$$d! apparently I don't have permission to add comments so...

After giving this some thought and trying out a few things I've decided to use Arrays for this; I could just have 3 int variables but I need to practice working with arrays.

I had some issues with the array's index when I used the method in the example by @Chronos-L so I'm gonna try a variation on that approach using array.sort and array.reverse to achieve the same end result, I hope.

This is the idea:

if score > array[2]
array[2] = score
array.sort
array.reverse

I will keep working on this and will post my solution hopefully sooner than later.

After that, I must figure out how to store the array into PlayerPreferences. I gather it will be tricky but feel it will be good training for when I will eventually have to save a top 100 online; Let the fun begin!

avatar image donimation donimation · Sep 29, 2016 at 07:25 PM 0
Share

Except that "oh wait!" C# doesn't support array.sort() only JS does :| [or maybe it does and I'm just doing it wrong:]

avatar image donimation donimation · Sep 29, 2016 at 07:41 PM 0
Share

Lists seem more appealing now. I'm worried about adding items/indexes to it indefinitely but I'm sure there's some way to prevent that. I really want to get the array method working but for the sake of getting something working at all soon it looks I might just use Lists :| worth a try...

avatar image Happy-Zomby donimation · Sep 29, 2016 at 08:55 PM 0
Share

If you are worried about an infinity loop - you can just linked your add to list to a boolean and switch that boolean if your list count exceeds a certain number.

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

61 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

Related Questions

How to arrange list 3 Answers

A node in a childnode? 1 Answer

Is there a way to remove array entries in the editor? 4 Answers

Limiting size of data structures in editor 1 Answer

Nullreferenceexception, Struct, Array, List 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