- Home /
Why is this script not moving my character and constantly getting this error given below,why is this script not moving my character
NullReferenceException: Object reference not set to an instance of an object playermovement.FixedUpdate () (at Assets/playermovement.cs:22)
[1]: /storage/temp/172162-screenshot-16.png
,This is the script
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class playermovement : MonoBehaviour { public CharacterController2D controller; float horizontalmove = 0f; public float runspeed = 40f;
// Update is called once per frame
void update () { horizontalmove = Input.GetAxisRaw("Horizontal") * runspeed; }
void FixedUpdate ()
{
controller.Move(horizontalmove * Time.fixedDeltaTime, false, false);
}
},
Answer by Disastercake · Dec 07, 2020 at 04:15 PM
Couple things to note: 1. You'll need to change the method "update()" to be a capital U. So... "Update()". Capitalization matters in C#, so Unity won't read the lowercase update as the correct Update method. 2. The object "controller" is probably empty in your inspector, which means the code crashes when it tries to access the object that doesn't exist.
You can fix #2 by: 1. Going to your scene view 2. Selecting the GameObject with this script 3. Looking at the inspector: locate the empty slot called "controller". 4. Dragging the GameObject with the CharacterController into that controller slot.
The above steps will allow your code to reference that GameObject.
Answer by qsp18 · Dec 07, 2020 at 04:08 PM
Probably you didnt referenced the controller. You have to assign the Character Controller in the Inspector in the Unity Editor. Just drag and drop in there the Character Controller