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

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.

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);
     }
 }