Null Reference

Use code-tags when posting code, not plain-text. You can now edit your post and code-tags too.

A NullReferenceException is you creating a reference field such as “rb” above but NOT setting it to reference anyway at all. In C# a reference is where you have a field (etc) that is a Class type. For these, you have references to the instance of the Class such as the specific GameObject or Component or your own Classes. The opposite are value types such as Vector2 etc. These are structs and do not use references, they copy their contents so each field is a copy.

The error tells you the exact line and column you do this so it should be super simple for you to debug it and not have to post on the forums asking others to do so.

So:

I suspect you mean to assign the Rigidbody2D component to the “rb” field here. This isn’t what you’re doing!! If you want to assign something then it should be pretty obvious you should be should be using the assignment operator i.e. “rb = GetComponent();” You will actually get a NullReferenceException here because you’re using “rb” which is NULL but you didn’t mention it.

You mention the one no line 21 “rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);” but that’s because “rb” is still NULL because you didn’t assign anything to it.

For the future, when you see this, debug your code as it’ll be you not assigning something. Also, you posted this on the 2D forums but it has nothing to do with 2D, you should post stuff like this on the scripting forums.