-1

I get this error message in the following line but I don't know what I'm doing wrong.

 Scorelist.Add(entry.StatValue);

Error CS0120: An object reference is required for the non-static field, method, or property 'Game1.Scorelist'

How can I fix the issue?

  public List<int> Scorelist = new List<int>();

  NewClient();

  public async void NewClient()
  {
      await DoReadLeaderboard();
  }

    private static async Task DoReadLeaderboard()
    {
        // Get Leaderboard Request
        var result = await PlayFabClientAPI.GetLeaderboardAsync(new GetLeaderboardRequest()
        {
            // Specify your statistic name here
            StatisticName = "TestScore",
            // Override Player Profile View Constraints and fetch player DisplayName and AvatarUrl
            ProfileConstraints = new PlayerProfileViewConstraints()
            {
                ShowDisplayName = true,
                ShowAvatarUrl = true
            }
        });


        if (result.Error != null)
        {
            // Handle error if any
            Console.WriteLine(result.Error.GenerateErrorReport());
        }
        else
        {
            // Traverse the leaderboard list
            foreach (var entry in result.Result.Leaderboard)
            {                  
                Scorelist.Add(entry.StatValue);
            }
        }
    }
Jerry_Champ
  • 69
  • 2
  • 3
  • 7
  • 1
    DoReadLeaderboard is a static method but Scorelist is a class property. Is there a reason that DoReadLeaderboard needs to be static? – Jason May 23 '19 at 18:39
  • 5
    Possible duplicate of [CS0120: An object reference is required for the nonstatic field, method, or property 'foo'](https://stackoverflow.com/questions/498400/cs0120-an-object-reference-is-required-for-the-nonstatic-field-method-or-prop) – Ňɏssa Pøngjǣrdenlarp May 23 '19 at 18:41
  • @Jason It's the code from this tutorial. I'm not sure if it should be static or not. https://api.playfab.com/docs/tutorials/landing-tournaments/leaderboard-profile – Jerry_Champ May 23 '19 at 19:13
  • 1
    well, that code is not trying to modify an instance variable. FWIW this is basic C#, nothing to do with Xamarin – Jason May 23 '19 at 19:15

1 Answers1

2

You're using thje property Scorelist, but this isn't a static property, and you don't have an instance of the class. You may think that because you're calling it from member method it's OK, but because this method is static, it's not. You have 3 solutions:

1) Make DoReadLeaderboard() non-static:

private async Task DoReadLeaderboard()

2) Make Scorelist static:

public static List<int> Scorelist = new List<int>();

3) Create an instance of the class, and access it's Scorelist:

var instance = new <<ClassName>>();
instance.Scorelist.Add(entry.StatValue);
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77