Как я могу получить доступ к счету игрока после окончания раунда? - PullRequest
0 голосов
/ 03 мая 2020

Я довольно новый программист, пытающийся сделать довольно простую игру, используя MonoGame в C#. Моя проблема в том, что я хочу получить доступ к счету игрока после его смерти, но я не уверен, как это сделать. Именно с этой строкой я борюсь: if (highscore.EnterUpdate(gameTime, player.Points)) //'player.Points' is my guess on how I access the points the player got in the game, but it's probably supposed to be something else. Я хочу получить доступ к точкам, потому что тогда я могу добавить их в свой список рекордов.

При запуске игры я получаю сообщение об ошибке: "System.NullReferenceException: 'Ссылка на объект, не установленная для экземпляра объекта' 'player', была нулевой." в строке, упомянутой выше, player.Points.

Буду признателен Помогите! (Я не знаю, относится ли весь приведенный ниже код к решению этой проблемы, но я старался изо всех сил. Возможно, вам нужно больше?)

//File name: Game1.cs

    public class Game1 : Game
    {
        HighScore highscore;
        Player player;

        protected override void Update(GameTime gameTime)
        {
            switch (GameElements.currentState)
            {
                //...
                    switch (currentState)
                    {
                        case State.EnterHighScore:
                            if (highscore.EnterUpdate(gameTime, player.Points)) //here
                                currentState = State.PrintHighScore;
                            break;
                        default:
                            //...
                    }
            }
        }
    }
//File name: GameElements.cs
//Example

            foreach(GoldCoin gc in goldCoins.ToList()) //everytime the player collides with a coin
            {
                if (gc.IsAlive)
                {
                    gc.Update(gameTime);
                    if (gc.CheckCollision(player))
                    {
                        goldCoins.Remove(gc);
                        player.Points++; //the score increases when you collect a coin, because of this i assumed 'player.Points' was to be used in the code above.
                    }
                }
                else goldCoins.Remove(gc);
            }
//File name: Player.cs
    public class Player : PhysicalObject
    {
        int points = 0;
        //...
        public int Points //here, I assumed I could get the total score from this property?
        {
            get { return points; }
            set { points = value; }
        }
    }
//File name: HighScore.cs

class HSItem //might not be relevant, HSItem contains data about a person in the highscore list
{
    string name;
    int points;

    public string Name { get { return name; } set { name = value; } }

    public int Points { get { return points; } set { points = value; } }

    public HSItem(string name, int points)
    {
        this.name = name;
        this.points = points;
    }
}
//...
    void Add(int points) //here, is called from EnterUpdate()
    {
        HSItem temp = new HSItem(name, points);
        highscore.Add(temp); //Add() in this case belongs to List
        Sort();

        if (highscore.Count > maxInList)
        {
            highscore.RemoveAt(maxInList);
        }
    }

    public bool EnterUpdate(GameTime gameTime, int points) //here, 
    { 
        char[] key = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                       'L', 'M', 'N', 'O', 'P',  'Q', 'R', 'S', 'T', 'U',
                       'V', 'X', 'Y', 'Z'};

        if (CheckKey(Keys.Down, gameTime))
        {
            key_index++;
            if (key_index >= key.Length)
                key_index = 0;
        }

        if (CheckKey(Keys.Up, gameTime))
        {
            key_index--;
            if (key_index <= 0)
                key_index = key.Length - 1;
        }

        if (CheckKey(Keys.Enter, gameTime))
        {
            name += key[key_index].ToString();
            if (name.Length == 3)
            {
                Add(points); //here
                name = "";
                currentChar = "";
                key_index = 0;
                return true;
            }
        }
        currentChar = key[key_index].ToString();
        return false;
    }
//...

1 Ответ

2 голосов
/ 07 мая 2020

Убедитесь, что вы присвоили Game1.player где-то в вашем коде. Переменные в C# имеют значение по умолчанию до тех пор, пока вы не назначите их явно, а для классов по умолчанию - null. Вам нужно позвонить player = new Player() куда-нибудь, прежде чем вы получите доступ к player, если вы еще этого не сделали.

...