JediMan
JediMan

Reputation: 43

Method "AddForce()" isn't working on my object

I tried to add force on the object called 'simple banana' but it isn't working. There is my code :

simpleBanana.GetComponent<Rigidbody>().AddForce(Vector3.back * 10000f, ForceMode.Impulse);

Insert "Debug.Log (" ... ");" on the next line works. The mass of the object is 1, the object is not kinematic

Upvotes: 0

Views: 960

Answers (1)

Marcos Defina
Marcos Defina

Reputation: 125

First and most important: this way you are getting rigidbody will cause low performance. GetComponent is a very expensive method, never do it on Update, do it in void Setup, saving it to an object of RigidBody type, like in the API reference:

https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html

Second: I think it can be a reference problem. I had a lot of trouble with it when I was starting. Be sure simpleBanana is the object which contains the RigidBody. If your reference to that RigidBody is not dragging it and dropping it, be sure to navigate at simpleBanana before applying GetComponent.

Like if your script in on simplePotato, and you trying to access simpleBanana, do something like this:

RigidBody simpleBanana = GameObject.Find('simpleBanana').GetComponent<RigidBody>();

or if simpleBanana is child of simplePotato:

RigidBody simpleBanana = this.transform.GetChild(index_of_the_child).GetComponent<RigidBody>();

After getting the reference right, you can add whatever force you want.

But remember to get components only on void Setup.

Upvotes: 1

Related Questions