0

Ошибка NullReferenceException: Object reference not set to an instance of an object Game.UpdateUI () (at Assets/Scripts/Game.cs:40) Game.Update () (at Assets/Scripts/Game.cs:34)

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class Game : MonoBehaviour
{
    public static int gridWidth = 10;
    public static int gridHeight = 20;

    public static Transform[,] grid = new Transform[gridWidth,gridHeight];

    public int scoreOneLine = 40;
    public int scoreTwoLine = 100;
    public int scoreThreeLine = 300;
    public int scoreFourLine = 1200;

    public Text hud_score;

    private int numberOfRowsThisTurn = 0;

    private int currentScore = 0;

    // Start is called before the first frame update
    void Start()
    {
        SpawnNextTetromino ();
    }

    void Update () {

        UpdateScore ();

        UpdateUI ();

    }

    public void UpdateUI () {

        hud_score.text = currentScore.ToString();
    }

    public void UpdateScore () {

        if (numberOfRowsThisTurn > 0) {

            if (numberOfRowsThisTurn == 1) {

                ClearedOneLine ();

            } else if (numberOfRowsThisTurn == 2) {

                ClearedTwoLines ();

            } else if (numberOfRowsThisTurn == 3) {

                ClearedThreeLines ();

            } else if (numberOfRowsThisTurn == 4) {

                ClearedFourLines ();

            }

            numberOfRowsThisTurn = 0;
        }
    }

    public void ClearedOneLine () {

        currentScore += scoreOneLine;

    }

    public void ClearedTwoLines () {

        currentScore += scoreTwoLine;

    }

    public void ClearedThreeLines () {

        currentScore += scoreThreeLine;

    }

    public void ClearedFourLines () {

        currentScore += scoreFourLine;

    }

    public bool CheckIsAboveGrid (tetrismino tetromino) {

        for (int x = 0; x < gridWidth; ++x) {

            foreach (Transform mino in tetromino.transform) {

                Vector2 pos = Round (mino.position);

                if (pos.y > gridHeight -1) {

                    return true;
                }
            }
        }

        return false;
    }

    public bool IsFullRowAt (int y) {

        for (int x = 0; x < gridWidth; ++x) {

            if (grid[x, y] == null) {

                return false;
            }
        }

        numberOfRowsThisTurn++;

        return true;
    }

    public void DeleteMinoAt (int y) {

        for (int x = 0; x < gridWidth; ++x) {

            Destroy (grid[x, y].gameObject);

            grid[x, y] = null;
        }  
    }

    public void MoveRowDown (int y) {

        for (int x = 0; x < gridWidth; ++x) {

            if (grid[x, y] != null) {

                grid[x, y-1] = grid[x, y];

                grid[x, y] = null;

                grid[x, y-1].position += new Vector3(0, -1, 0); 
            }
        }
    }

    public void MoveAllRowDown (int y) {

        for (int i = y; i < gridHeight; ++i) {

            MoveRowDown (i);
        }
    }

    public void DeleteRow () {

        for (int y = 0; y < gridHeight; ++y) {

            if (IsFullRowAt(y)) {

                DeleteMinoAt(y);

                MoveAllRowDown(y + 1);

                --y;
            }
        }
    }

    public void UpdateGrid (tetrismino tetromino) {

        for (int y = 0; y < gridHeight; ++y) {

            for (int x = 0; x < gridWidth; ++x) {

                if (grid[x, y] != null) {

                    if (grid[x,y].parent == tetromino.transform) {

                        grid[x, y] = null;
                    }
                }
            }
        }

        foreach (Transform mino in tetromino.transform) {

            Vector2 pos = Round (mino.position);

            if (pos.y < gridHeight) {

                grid[(int)pos.x, (int)pos.y] = mino;
            }
        }
    }

    public Transform GetTransformGridPosition (Vector2 pos) {

        if (pos.y > gridHeight -1) {

            return null;

        } else {

            return grid[(int)pos.x, (int)pos.y];
        }
    }

    public void SpawnNextTetromino () {

        GameObject nextTetromino = (GameObject)Instantiate(Resources.Load(GetRandomTetromino(), typeof(GameObject)), new Vector2(5.0f, 20.0f), Quaternion.identity);
    }

    public bool  CheckIsInsideGrid (Vector2 pos) {

        return ((int)pos.x >= 0 && (int)pos.x < gridWidth && (int)pos.y >= 0);
    }

    public Vector2 Round (Vector2 pos) {

        return new Vector2 (Mathf.Round(pos.x), Mathf.Round(pos.y));
    }

    string GetRandomTetromino () {

        int randomTetromino = Random.Range(1, 8);

        string randomTetrominoName = "Prefabs/Tetromino_T";

        switch (randomTetromino) {

        case 1:
            randomTetrominoName = "Prefabs/Tetromino_T";
            break;
        case 2:
            randomTetrominoName = "Prefabs/Tetromino_I";
            break;
        case 3:
            randomTetrominoName = "Prefabs/Tetromino_O";
            break;
        case 4:
            randomTetrominoName = "Prefabs/Tetromino_J";
            break;
        case 5:
            randomTetrominoName = "Prefabs/Tetromino_L";
            break;
        case 6:
            randomTetrominoName = "Prefabs/Tetromino_S";
            break;
        case 7:
            randomTetrominoName = "Prefabs/Tetromino_Z";
            break;
        }

        return randomTetrominoName;
    }

    public void GameOver () {

        SceneManager.LoadScene ("GameOver");
    }
}
  • public Text hud_score; - т.е. это поле сейчас равно null. А вы пытаетесь hud_score.text = currentScore.ToString();. Надо бы сначала проинициализировать hud_score, а потом уже запрашивать у него свойство Text. – Bulson Dec 09 '19 at 20:40

1 Answers1

1

Причина возникновения ошибки NullReferenceException это отсутствие объекта в: Text hud_score;

Решение: Обратите внимание на public Text hud_score; его инициализация производиться в Unity, просто вернитесь в Unity и укажите в используемом коде hud_score объект с помощью перетаскивания или выбором объекта Text с текущей сцены.

Либо вы можете изначально прописать используемый объект в коде: public Text hud_score = GameObject.Find("Тут_имя_объекта_выводящего_текст").GetComponent<Text>();

Nvaho
  • 11