Spaceship movement in Unity

Viewed 165

So I am working on a project where I have to move a spaceship in Unity. Currently my biggest problem is getting used to the new input system of Unity. I want to create most of the actions in the script since they seem to be easier to manipulate in code. I got some code creating InputMap, InputAction and InputAsset but every time I try playmode it gives me an NullReferenceException for the variable forwardAction as soon as it's called the first time. Does anyone know where the exception could come from?

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

public class ShipMovement : MonoBehaviour
{
    Rigidbody rb;
    InputAction forwardAction;
    [SerializeField] float force;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        InputActionAsset asset = new InputActionAsset();
        InputActionMap map = new InputActionMap("Spaceship");
        InputAction forwardAction = new InputAction("Move Forward", type: InputActionType.Button, binding: "<Keyboard>/w");
        map.AddAction("Move Forward");
        asset.AddActionMap(map);
        map.Enable();
    }
    private void FixedUpdate()
    {
        MoveForward();
    }
    /// <summary>
    /// Adds forward force to spaceship object.
    /// Early return if button is not pressed in frame.
    /// On first press and key held force gets added every frame.
    /// </summary>
    public void MoveForward()
    {
        if (forwardAction.phase == InputActionPhase.Waiting)
            return;
        if (forwardAction.WasPressedThisFrame())
        {
            rb.AddForce(Vector3.forward * force * Time.fixedDeltaTime, ForceMode.Acceleration);
        }
        else if (forwardAction.IsPressed())
        {
            rb.AddForce(Vector3.forward * force * Time.fixedDeltaTime, ForceMode.Acceleration);
        }
    }
}

0 Answers
Related