Stuck with AddForceAtPostion (new to C#)

Can anyone tell me what I did wrong with this code? It does not work. I get "error CS0120: An object reference is required to access non-static member `UnityEngine.Rigidbody.AddForceAtPosition(UnityEngine.Vector3, UnityEngine.Vector3, UnityEngine.ForceMode)’

What object reference? This script is attached to the object.

public float forceX=0;
public float forceY=0;
public float forceZ=0;
public Vector3 pos=new Vector3(0,0,0);
	
void FixedUpdate () {

	Rigidbody.AddForceAtPosition(Vector3(forceX,forceY,forceZ), transform.position - pos);		
	}

I fixed the code in the quote above. AddForceAtPosition is not a static method: it cannot be called on the type Rigidbody, but on an instance of said type. If you’ve used a different language, like, say, Objective-C, static methods are like class methods. I’m guessing that functionally you wanted “rigidbody” with a lowercase “r”, because that gives you the specific rigidbody attached to the game object your script is attached to. Finally, you needed to use “new” when creating your Vector3. I think that’s everything.

Thanks - that was a helpful post. Yes I did want lowercase “r” but as it didn’t work I’d been playing around with it.

My problem is I don’t understand what static methods are. But at least I know what I don’t know now!

Glad to help. A static method is called on the type itself, rather than an instance of a type. So, let’s say you have a class called Panda. Panda defines a normal, nonstatic method called Eat(Food treat), which consumes some food and returns how hungry the panda still is. You would call it like this.

Panda bobby = new Panda();
int hunger = bobby.Eat(bamboo);

That would tell the specific Panda, bobby, to eat. Now, consider that the Panda class defines having a static method called Population(), which returns an integer telling us how many pandas are in existence. A static method is not specific to any instance of a class, but the type itself. You would call it like this.

int numberOfPandas = Panda.Population();

The first method is some action involving a specific panda, so we need an actual panda before we can use it, while the second method, which is static, is an action involving the type itself, so we use the class’s name instead. This is why your code wouldn’t work; you wanted to add a force to a specific rigidbody, but were treating the method as static and calling it on the Rigidbody class. You can think of it as a species, and an animal belonging to said species. You can tell a dog to sit, but you can’t tell Canis lupus familiaris to sit. Hopefully, that clears things up. :slight_smile: