Как мне решить эту ошибку? Поле никогда не назначается и всегда будет иметь нулевое значение - PullRequest
0 голосов
/ 31 мая 2019

Я создал 4 сценария c #. Когда я запускаю игру 2d unity, я вижу это предупреждение в своей консоли.

"Активы \ Скрипты \ GameHandler.cs (7,34): предупреждение CS0649: Поле GameHandler.car никогда не назначается, и всегда будет иметь значение по умолчанию null "

Я создаю игру, похожую на змею, используя сценарии c # в unity 2d. Никогда раньше не использовал Unity или C #, это мой первый проект. Пока все идет хорошо, но я продолжаю получать это предупреждение, которое приводит к сбою моей игры. Я приложил 2 моих скрипта, первый обработчик игры, где эта проблема, и я думаю, что это относится к классу Car, который я прикрепил ниже. Это много кода, поэтому я прошу прощения, я просто понятия не имею.

public class GameHandler : MonoBehaviour
{
    [SerializeField] private Car car;

    private LevelGrid levelGrid;

    // Start is called before the first frame update
    private void Start()
    {
        Debug.Log("GameHandler.Start");

        //GameObject carHeadGameObject = new GameObject();
        //SpriteRenderer carSpriteRenderer = carHeadGameObject.AddComponent<SpriteRenderer>();
        //carSpriteRenderer.sprite = GameAssets.instance.carHeadSprite;

        levelGrid = new LevelGrid(20,20); //width,height of grid

        car.Setup(levelGrid);
        levelGrid.Setup(car);
    }


    }
--------------------------------------
    using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Car : MonoBehaviour
{
    private enum Direction
    {
        Left,
        Right,
        Up,
        Down
    }

    private enum State
    {
        Alive,
        Dead
    }

    private State state;
    private Vector2Int gridPosition; //uses ints instead of floats useful for grid positiioning
    private float gridMoveTimer; //time remaining until next movement
    private float gridMoveTimerMax; // time between moves

    private Direction gridMoveDirection;

    private LevelGrid levelGrid;
    private int carsize;
    private List<CarMovePosition> carMovePositionList;
    private List<Carsize> carSizeList;

    public void Setup(LevelGrid levelGrid) {
        this.levelGrid = levelGrid;
    }

    private void Awake() {
        gridPosition = new Vector2Int(10,10); //initalise grid position into middle of grid 
        gridMoveTimerMax = .2f; //car to move along grid every 1/2 second
        gridMoveTimer = gridMoveTimerMax; //0f
        gridMoveDirection = Direction.Right; // default move right

        carMovePositionList = new List<CarMovePosition>();
        carsize = 0;
        carSizeList = new List<Carsize>();

        state = State.Alive;
    }

    private void Update()
    {
        switch (state)
        {
            case State.Alive:
            HandleInput(); // checks for keyboard input
            HandleGridMovement();
                break;
            case State.Dead:
                break;
        }



    }


    private void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            if (gridMoveDirection != Direction.Down)
            { // can only go up if not going down
                gridMoveDirection = Direction.Up;
            }
        }
        //return true on up arrow press

        if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            if (gridMoveDirection != Direction.Up)
            {
                gridMoveDirection = Direction.Down;

            }
        }
        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            if (gridMoveDirection != Direction.Right)
            {
                gridMoveDirection = Direction.Left;
            }
        }
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            if (gridMoveDirection != Direction.Left)
            {
                gridMoveDirection = Direction.Right;
            }
        }
    }

    private void HandleGridMovement()
    {
        gridMoveTimer += Time.deltaTime; // amount of time left since last update
        if (gridMoveTimer >= gridMoveTimerMax)//if true then 1 sec since last move
        {
            gridMoveTimer -= gridMoveTimerMax;

            CarMovePosition previousCarMovePosition = null;

            if (carMovePositionList.Count > 0){
                previousCarMovePosition = carMovePositionList[0];
            }

            CarMovePosition carMovePosition = new CarMovePosition(previousCarMovePosition, gridPosition, gridMoveDirection);
            carMovePositionList.Insert(0, carMovePosition);

            Vector2Int gridMoveDirectionVector;
            switch (gridMoveDirection) {
                default:
                case Direction.Right: gridMoveDirectionVector = new Vector2Int(+1, 0);break;
                case Direction.Left: gridMoveDirectionVector = new Vector2Int(-1, 0); break;
                case Direction.Up: gridMoveDirectionVector = new Vector2Int(0, +1); break;
                case Direction.Down: gridMoveDirectionVector = new Vector2Int(0, -1); break;
            }
            gridPosition += gridMoveDirectionVector;

            bool cargotfuel = levelGrid.Trycarfuel(gridPosition);
            if (cargotfuel)
            {
                carsize++;
                CreateCarSize();
            }


            if (carMovePositionList.Count >= carsize + 1)
            {
                carMovePositionList.RemoveAt(carMovePositionList.Count - 1);
            }

            foreach (Carsize carsize in carSizeList)
            {
                Vector2Int carSizeGridPosition = carsize.GetGridPosition();
                if (gridPosition == carSizeGridPosition)
                {

                    //print("Gameover");
                    state = State.Dead;
                }
            }


            transform.position = new Vector3(gridPosition.x, gridPosition.y);
            //move transform based on location of gridPosition

            transform.eulerAngles = new Vector3(0, 0, GetAngleFromVector(gridMoveDirectionVector) - 90);
            //modify transform to face the correct way

            UpdateCarSize();

        }
    }


    private void CreateCarSize()
    {
        carSizeList.Add(new Carsize(carSizeList.Count));
    }

    private void UpdateCarSize(){
        for (int i = 0; i < carSizeList.Count; i++) {
            carSizeList[i].SetCarMovePosition(carMovePositionList[i]);
            //carSizeList[i].SetGridPosition(carMovePositionList[i].GetGridPosition());
        }
    }

    private float GetAngleFromVector(Vector2Int dir)
    {
        float n = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
        if (n < 0) n += 360;
        return n;
    }

    public Vector2Int GetGridPosition()
    {
        return gridPosition;
    }

    //returns car list of positions full with body
    public List<Vector2Int> Getcargridpositionlist(){
        List<Vector2Int> gridPositionList = new List<Vector2Int>() { gridPosition };
        foreach (CarMovePosition carMovePosition in carMovePositionList)
        {
            gridPositionList.Add(carMovePosition.GetGridPosition());
        }
        return gridPositionList;
    }

    private class Carsize{

        private CarMovePosition carMovePosition;
        private Transform transform;

        public Carsize(int sizeIndex){
            GameObject carsGameObject = new GameObject("carBody", typeof(SpriteRenderer));
            carsGameObject.GetComponent<SpriteRenderer>().sprite = GameAssets.instance.carsSprite;
            carsGameObject.GetComponent<SpriteRenderer>().sortingOrder = -sizeIndex;
            transform = carsGameObject.transform;
        }

        public void SetCarMovePosition(CarMovePosition carMovePosition){
            this.carMovePosition = carMovePosition;

            transform.position = new Vector3(carMovePosition.GetGridPosition().x, carMovePosition.GetGridPosition().y);

            float angle;
            switch (carMovePosition.GetDirection()){
            default:
                case Direction.Up:// going up
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = 0; break;
                        case Direction.Left: // was going left
                            angle = 0 + 45; break;
                        case Direction.Right:// was going right
                            angle = 0 - 45; break;
                    }
                    break;
                case Direction.Down:
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = 180; break;
                        case Direction.Left:
                            angle = 180 + 45; break;
                        case Direction.Right:
                            angle = 180 - 45; break;
                    }
                    break;
                case Direction.Left:
                    switch (carMovePosition.GetPreviousDirection()){
                        default:
                            angle = -90; break;
                        case Direction.Down:
                            angle = -45; break;
                        case Direction.Up:
                            angle = 45; break;
                    }
                    break;
                case Direction.Right: // going right
                    switch (carMovePosition.GetPreviousDirection()){
                    default:
                        angle = 90; break;
                    case Direction.Down: // previously going down
                        angle = 45; break;
                    }
                    break;
            }
            transform.eulerAngles = new Vector3(0, 0, angle);
        }

        public Vector2Int GetGridPosition()
        {
            return carMovePosition.GetGridPosition();
        }
    } 

    private class CarMovePosition{

        private CarMovePosition previousCarMovePosition;
        private Vector2Int gridPosition;
        private Direction direction;

        public CarMovePosition(CarMovePosition previousCarMovePosition, Vector2Int gridPosition, Direction direction){
            this.previousCarMovePosition = previousCarMovePosition;
            this.gridPosition = gridPosition;
            this.direction = direction;
        }

        public Vector2Int GetGridPosition(){
            return gridPosition;
        }

        public Direction GetDirection(){
            return direction;
        }

        public Direction GetPreviousDirection(){
            if (previousCarMovePosition == null){
                return Direction.Right;
            } else {
                return previousCarMovePosition.direction;
            }
        }

    }
    }

Это может быть случай щелчка / перетаскивания чего-либо в самом unity2d, что я должен был сделать раньше. Но сейчас я так потерян.

Ответы [ 2 ]

4 голосов
/ 31 мая 2019

Это говорит вам, что

[SerializeField] private Car car; 

не инициализируется в коде, но это нормально, потому что вы инициализируете его в инспекторе.Если вы хотите избавиться от предупреждения, вы можете установить его в null:

[SerializeField] private Car car = null;
0 голосов
/ 31 мая 2019

Предупреждение появляется, потому что вы не инициализируете объект "автомобиль", и ваша игра вылетает, когда он пытается использовать этот объект, которому не присвоено значение.

Вы должны инициализировать любой объект перед его использованием, чтобы избежать сбоев.

Итак, ваш метод Start () должен быть таким:

private void Start()
{
    Debug.Log("GameHandler.Start");

    car = new Car(); // you must initialize objects before using them!

    //GameObject carHeadGameObject = new GameObject();
    //SpriteRenderer carSpriteRenderer = carHeadGameObject.AddComponent<SpriteRenderer>();
    //carSpriteRenderer.sprite = GameAssets.instance.carHeadSprite;

    levelGrid = new LevelGrid(20,20); //width,height of grid

    car.Setup(levelGrid);
    levelGrid.Setup(car);
}

Надеюсь, это поможет вам!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...