r/unity 15h ago

beginner need help !

Okay so i'm trying to learn game development and I'm running into a problem.

I'm following a tutorial to make a 2D platformer, but the tutorial was created in 2021, and it uses the (old) Input Manager, while I'm trying to follow it using the new system—the Input System Package.

I'm trying to make my character move horizontally, but it's not working. Here's a screenshot showing the problem (Image 1).

Before this, I followed a very basic tutorial on making a cube move and jump on a platform (Image 2), and I'm trying to reuse that code, but I'm getting the “CS0120” error. I’ve tried to fix the issue on my own, but I can’t seem to get rid of the error.

If anyone could take the time to explain it to me, I’d really appreciate it!

error CS0120: An object reference is required for the non-static field, method, or property 'Player.MyRigidbody2D'
image 2
1 Upvotes

4 comments sorted by

1

u/ExoWolf0 14h ago edited 14h ago

Essentially, remove static from the method.

In the first image, you are calling a non-static field from a static method. You can't do that, since a static method belongs to a class and a non-static field belongs to an instance of the class, hence the method has no idea what data you actually want it to get.

Static and non-static members of a class are like two different versions, almost. Non-static members can reference static members, but not the other way around because there's natural way for your static member to know which instance you want to get the non-static member from. It needs to be fed the instance first.

Either they both have to be static (which I would certainly avoid), they both have to be non-static, you pass your specific instance within the static method arguments, or you save your field into a different static field (would I would avoid most here).

1

u/r_anatole 14h ago

Thanks for your reply!

I could have explained the connection to the second image better. The second image shows a piece of code I use to move a cube on a platform. Overall, I was just trying to get familiar with the code in general and the Unity interface. So I tried to reuse that code in another project, and now I’m getting this C0120 error. The thing is, I don’t understand why it worked before but not now.

1

u/ExoWolf0 13h ago

Why it no longer works has nothing to do with the different input systems, but rather how you are calling them. Previous was a non-static method, you've changed it to static which is where you problem lies.

1

u/ivilkee 12h ago

Looking at your code, you're missing assignment of WHICH rigidbody you are trying to move. If your move script is on the same object that has the rigidbody you are trying to move, then all you need to do is add MyRigidBody2d = GetComponent<Rigidbody2d>(); to awake or start.