Hi, so, I have been trying to make my first 3D game and I’ve been attempting to make a character controller and I’ve seen a couple other threads however they don’t solve my problem
using System.Collections;
using UnityEngine;
public class Movement : MonoBehaviour
{
Rigidbody rb;
[SerializeField] float MovementSpeed = 5f;
[SerializeField] float JumpHeight = 5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
//Movement
if (Input.GetKey(KeyCode.W))
{
//Next line has a bug
rb.AddForce(transform.forward * MovementSpeed);
}
if (Input.GetKey(KeyCode.S))
{
//Next line has a bug
rb.AddForce(-transform.forward * MovementSpeed);
}
if (Input.GetKey(KeyCode.A))
{
//Next line has a bug
rb.AddForce(-transform.right * MovementSpeed);
}
if (Input.GetKey(KeyCode.D))
{
//Next line has a bug
rb.AddForce(transform.right * MovementSpeed);
}
}
}
So yeah, and help is appreciated! I’ve been trying to fix this but I don’t see what’s wrong, or as I’m new to this c# thingy it’s a dumb question
(Also, I have a RigidBody in the GameObject that this script is in)
You will meet nullreference error plenty of times, so you should really check what Kurt Dekker provided. But if you want quick answer…
You always need to write it like that:
Just to get component that you wrote, because compiler doesn’t know which object’s is Rigidbody. By writing rb = GetComponent(), you basically saying that “rb” equals to rigidbody2d component, that is attached to a “movement” script’s gameobject.
But you can also drag and drop RB component in inspector. [SerializeField] private Rigidbody2D rb;
With that, you won’t need to write GetComponent in script, but you need to make sure that you dragged and dropped Rigidbody2D component in inspector. [SerializeField] basically serializes private field, so you can see it in ispector, but you can also make it public RigidBody rb, and it will do same thing.
Rather than pushing back on that comment, maybe you would like to absorb the first part of the reply which is the solution to your problem. You didn’t provide the line the error was on yet someone gave you the solution so kudos to them!