Error [Nullreferenceexception] - Unity in C#

Asked

Viewed 35 times

-1

My code is not working, causing the following error:

Nullreferenceexception

The point is to jump, but I can only walk:

public class player : MonoBehaviour
{
public float Speed;
private Rigidbody2D rig;
public float JumpForce;
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
Move();
Jump();
}

void Move()
{
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * Speed;
}

void Jump()
{
if(Input.GetButtonDown("Jump"))
{
rig.AddForce(new Vector2(0f, JumpForce), ForceMode2D.Impulse);
}

}
}
  • Hello Erick, welcome to [en.so]. I suggest you edit your question and add the criteria, from [Re], it is worth a lot to take a look, so you can elaborate a good question!

1 answer

1

Nullreferenceexception means that you are trying to do something with an object that has not been initialized.

In case you define an object of type Rigidbody2d

private Rigidbody2D rig;

But nowhere do you create an instance for that object. Something like:

rig = new Rigidbody2D()

So when you do:

rig.(QUALQUER_COISA)

You will receive a Nullreferenceexception

Browser other questions tagged

You are not signed in. Login or sign up in order to post.