如何解决此错误?字段从未分配,并且始终为空值

Ubi保护者

我创建了4个C#脚本。当我运行2D统一游戏时,我在控制台中看到此警告。

“ Assets \ Scripts \ GameHandler.cs(7,34):警告CS0649:从未将字段'GameHandler.car'分配给该字段,并且其默认值始终为null”

我正在统一2d中使用c#脚本创建类似于蛇的游戏。从未使用过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本身中单击/拖动某些内容的情况。但是我现在迷失了。

阿德里亚诺·奥利维拉(Adriano Oliveira)

发生警告是因为您没有初始化对象“ car”,并且当它尝试使用未分配任何值的对象时,游戏会崩溃。

您必须在使用任何对象之前对其进行初始化,以避免崩溃。

因此,您的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);
}

希望对您有所帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

构造函数DI-字段从未分配,并且将始终具有其默认值

字段ModifyDate从未分配给它,并且将始终具有其默认值0

c#中的结构给出警告字段从未分配给字段,并且将始终具有其默认值0

ElasticSearch:未分配的碎片,如何解决?

如何解决此错误?字段“ id”应为数字,但为“ aapl”

如何解决“不能将类型为((FirebaseUser)→空”的值分配给类型为((AuthCredential)→空”的变量。”

如何解决此错误“方法'/'被调用为空”

Malloc错误“无法分配区域”失败,错误代码为12。知道如何解决此问题吗?

如何解决此错误?

如何解决此错误?

如何解决此问题,我的登录页面无法连接,并且继续出现此错误

如何解决Redshift错误:“缺少非空字段的数据”?

如何解决此错误:“尝试索引?(数字值)”

如何解决在Verilog中分配多个值错误的问题?

如何解决:使用未分配的本地IWebElement变量

如何解决“属性:.......不能设置为空”错误

如何解决错误:查询中的查询为空?

如何解决“ System.ArgumentException:值不能为null或为空。参数名称:contentPath”此错误?

如何解决无法读取空错误的属性“值”?

如何解决此错误:分段错误?

如何解决“无法转换'(CGFloat)->数据类型的值?” 此代码的预期参数类型为“数据””错误?

在分配错误之前引用了Python局部变量,如何解决此错误?

如何解决此Java公证错误?

如何解决此JTextArea格式错误?

如何解决此Eclipse错误?

此查询中的错误:如何解决?

如何解决此Gradle错误?

在MiniZinc中如何解决此错误?

如何解决此OOP错误?