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 /
  • Help Room /
avatar image
0
Question by jimjames · Feb 16, 2016 at 01:41 AM · lists

Add to a List

I am having a hard time finding out how to add to this kind of list.

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 [System.Serializable]
 public class HighScore
 {
     public int score;
     public float timePlayed;
 }
 
 public class SomeClass : MonoBehaviour
 {
     public List<HighScore> highscores = new List<HighScore>();
 
     void Start()
     {
         highscores.Add(???); //this is the part I need help with
     }
 }


I usually use this when "highscores" is an array and just add what I need via inspector. Which works great. But I wish to make it dynamic at runtime and cant figure out how to add a new element this way with values.

FYI: This is as simple as I could make it for this question.

James

Comment
Add comment · Show 2
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 jimjames · Feb 16, 2016 at 02:00 AM 0
Share

This works but I think its kinda hacky:

  void Start()
     {
         //highscores.Add(???); //this is the part I need help with
         int temp = highscores.Count;
         highscores.Add(new HighScore());
         highscores[temp].score = 1234;
         highscores[temp].timePlayed = 1.234f;
     }

Was wondering if there is a better way? Also, what is this type of list called?

Thanks: James

avatar image EmHuynh jimjames · Feb 16, 2016 at 02:24 AM 1
Share

There are many ways of doing this. Here is a simple method:

     // Declare a HighScore variable so we can change it's value and then add it.
     HighScore newHighScore = new HighScore();
 
     void Start() {
         newHighScore.score = 1337;
         newHighScore.timePlayed = 2016;
         highscores.Add( newHighScore );
     }

2 Replies

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

Answer by Cherno · Feb 16, 2016 at 02:09 AM

Here is a handy link that explains a lot about Collections: Choosing the right collection type

This type of list is called a Generic List.

Declare your class with an initializer that accepts the required values:

   using UnityEngine;
  using System.Collections;
  using System.Collections.Generic;
  
  [System.Serializable]
  public class HighScore
  {
      public int score;
      public float timePlayed;

     //create an initializer. This one without parameters doesn't have to be declared if you declare no other initializers; it is always the default one for each custom class.
      public Highscore() {};
      //another one that accepts parameters
       public Highscore(int s, float t) 
      {
            score = s;
           timePlayed = t;
       };
  }
  
  public class SomeClass : MonoBehaviour
  {
      public List<HighScore> highscores = new List<HighScore>();
  
      void Start()
      {
          //use the initializer to directly create a new class instance with values
          highscores.Add(new Highscore(1234, 1.234f));
          //without the initializer you could also do it like this:
         highscores.Add(new Highscore() {score = 1234, timePlayed = 1.234});
       //you can also do it seperately, of course.
       Highscore myHighscore = new Highscore(1234, 1.234f);
         highscores.Add(myHighscore);
      }
  }




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 jimjames · Feb 16, 2016 at 02:25 AM 0
Share

Ahh yes, I have done it like that before but was trying to see if i didnt need to have a initializer. $$anonymous$$ake it as simple as possiable. The way you have it also allows for a custom sort(). Thank you for your answer.

avatar image jimjames · Feb 16, 2016 at 04:43 PM 0
Share

Here is a script that is working that also has a sort order add if anyone else is wondering.

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using System;
 
 [System.Serializable]
 public class HighScore : IComparable<HighScore>
 {
     //creating a custom sorting order
     public int CompareTo(HighScore other)
     {
         if (this.score > other.score)
             return 1;
         else if (this.score < other.score)
             return -1;
         else
             return 0;
     }
 
     public int score;
     public float timePlayed;
 
     public HighScore(int s, float t)
     {
         score = s;
         timePlayed = t;
     }
 }
 
 public class abcd : $$anonymous$$onoBehaviour
 {
     public List<HighScore> highscores = new List<HighScore>();
 
     void Start()
     {
         //1 way to .Add
         highscores.Add(new HighScore(2345, 2.345f));
 
         //another way to .Add
         HighScore newscroe = new HighScore(1234, 1.234f);
         highscores.Add(newscroe);
 
         //sorts the list by the cutom sorting order created inside "HighScore"
         highscores.Sort();
     }
 }

avatar image
1

Answer by philboyd · Feb 16, 2016 at 01:07 PM

Lists are collections of instances of objects.

You've started this process with the "Public class HighScore" block, however you don't actually have an INSTANCE of a highscore yet.

As a testing example, change your SomeClass:MonoBehaviour to be

  public List<HighScore> highscores = new List<HighScore>();
  public HighScore franksScore;
  void Start()
  {
      franksScore.score = 100;
      franksScore.timePlayed = 15.6;

      highscores.Add(franksScore); 
  }

This makes an INSTANCE of HighScore called franksScore that you can add.

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 jimjames · Feb 16, 2016 at 04:10 PM 0
Share

thanks this works great. never thought I could create a single var of "HighScore" . Gives me a few ideas. thanks again.

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

36 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

Related Questions

Using foreach to remove and delete bullet in List - C# 3 Answers

Is it possible to make a List into another List? C# 2 Answers

Updating and redrawing list objects - How? 0 Answers

Using the "Contain" method on a list with various variables. 0 Answers

Adding new spawned objects to a list? 0 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