带有新输入系统的Unity NullReferenceException错误

时间:2020-10-14 00:34:11

标签: c++ unity3d game-engine

我对团结还很陌生,因此,如果这是一个简单的解决方法,很抱歉,但我无法弄清楚。我收到null错误,与我的playerInputHandler有关。有人可以指出我要去哪里了吗?我会很感激。

错误:NullReferenceException:对象引用未设置为对象的实例 Mover.Update()(位于Assets / Scripts / Mover.cs:37)

PlayerInputHandler.cs

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.InputSystem;
using static UnityEngine.InputSystem.InputAction;

public class PlayerInputHandler : MonoBehaviour
{
    private PlayerInput playerInput;
    private Mover mover;

    public bool JumpPressed = false;
    public bool JumpPressing = false;

    private void Awake()
    {
        playerInput = GetComponent<PlayerInput>();
        var movers = FindObjectsOfType<Mover>();
        var index = playerInput.playerIndex;
        mover = movers.FirstOrDefault(m => m.GetPlayerIndex() == index);
    }
    
    public void OnMove(CallbackContext context)
    {
        if(mover != null)
            mover.SetInputVector(context.ReadValue<Vector2>());
    }

    public void OnJump(CallbackContext context)
    {
        if(mover != null)
        {
            if (context.started)
            {
                JumpPressing = true;
            }
            else if (context.canceled)
            {
                JumpPressed = true;
            }
        }    
    }

    void LateUpdate()
    {
        JumpPressing = false;
        JumpPressed = false;
    }
    
}

Mover.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Mover : MonoBehaviour
{

    [SerializeField] private float MoveSpeed, JumpSpeed;
    [SerializeField] private int playerIndex = 0;

    private Rigidbody2D rb;
    private Vector3 moveDirection = Vector3.zero;
    private Vector2 inputVector = Vector2.zero;
    PlayerInputHandler playerInputHandler;
    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        playerInputHandler = GetComponent<PlayerInputHandler>();
    }

    public int GetPlayerIndex()
    {
        return playerIndex;
    }

    public void SetInputVector(Vector2 direction)
    {
        inputVector = direction;
    }

    void Update()
    {

        Vector3 movement = new Vector3(inputVector.x, /*inputVector.y*/0, 0) * MoveSpeed * Time.deltaTime;
        transform.Translate(movement);

        if(playerInputHandler.JumpPressed)
        {
            rb.AddForce(new Vector4(0, JumpSpeed), ForceMode2D.Impulse);
        }
        if(playerInputHandler.JumpPressing)
        {
            Debug.Log("Are you going to jump?");
        } 
    }
}

1 个答案:

答案 0 :(得分:0)

playerInputHandler为null。确保在与Mover相同的对象上具有PlayerInputHandler组件。您还可以在Update()函数的开头添加Assert.IsNotNull(playerInputHandler);,以帮助防止此类不良行为。

相关问题