Hi there! New to scripting, new to Unity, total beginner here.
I am stuck in a tutorial I’ve been following diligently on YouTube, and am quite positive I’ve written my code exactly as shown. I am getting the following error:
NullReferenceException: Object reference not set to an instance of an object
PlayerController.MoveCrossHair () (at Assets/Scripts/PlayerController.cs:60)
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:48)
I’m really not getting it. Would appreciate any advice! Bonus points if you explain it like you would to a 5 year old, which I’m equating my C# understanding to…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Rewired;
public class RecompileTest : MonoBehaviour
{
void Update()
{
if (!ReInput.isReady) return;
Player p = ReInput.players.GetPlayer(0);
Debug.Log(p.GetButton("Fire"));
}
}
public class PlayerController : MonoBehaviour
{
public int playerId = 0;
public Animator animator;
public GameObject crossHair;
private Player player;
private void Awake()
{
player = ReInput.players.GetPlayer(playerId);
}
// Update is called once per frame
void Update()
{
Vector3 movement = new Vector3(Input.GetAxis("MoveHorizontal"), Input.GetAxis("MoveVertical"), 0.0f);
if (Input.GetButton("Fire"))
{
Debug.Log("FIRE!");
}
MoveCrossHair();
animator.SetFloat("Horizontal", movement.x);
animator.SetFloat("Vertical", movement.y);
animator.SetFloat("Magnitude", movement.magnitude);
transform.position = transform.position + movement * Time.deltaTime;
}
private void MoveCrossHair()
{
Vector3 aim = new Vector3(player.GetAxis("AimHorizontal"), player.GetAxis("AimVertical"), 0.0f);
if (aim.magnitude > 0.0f)
{
aim.Normalize();
crossHair.transform.localPosition = aim;
}
}
}