- Home /
Simple AddForce Scirpt help
Hi, I'm tyring to build a script, in Javascript, to have the User select an object(With a Rigidbody),andwhen they let go of a button, it will Add force and torque to the objects rigidbody. Here is My Script so far:
var Range : float; var AddedForce : float = 100; var AddedTorque : float = 10; var InputButton : String = "mouse 0";
private var SelectedObject : Rigidbody; function Update () { var Forward = transform.TransformDirection (Vector3.forward);
if(Input.GetButton(InputButton))
{
if(Physics.Raycast(transform.position, Forward, Range))
{
SelectedObject = RaycastHit.rigidbody;
}
if(Input.GetButtonUp(InputButton))
{
SelectedObject.AddForce(Vector3.forward * AddedForce);
SelectedObject.AddTorque (Vector3.up * AddedTorque);
}
}
}
Here is the error i am recieving: Assets/Script.js(20,53): BCE0020: An instance of type 'UnityEngine.RaycastHit' is required to access non static member 'rigidbody'.
I am not very good with raycast so can you please help me, thankyou.
Answer by Bunny83 · Mar 15, 2011 at 10:18 PM
You have to provide a variable of type RaycastHit. It's a struct and it doesn't have any static members. Do something like that:
var hit : RaycastHit;
if(Physics.Raycast(transform.position, Forward, hit, Range))
{
SelectedObject = hit.rigidbody;
}
else
{
SelectedObject = null; // if we aren't hit something reset the selection
}
Take a closer look at Physics.Raycast. There are a lot examples.
edit
Well you should also test if you even have a selected object:
if(SelectedObject != null && Input.GetButtonUp(InputButton))
{
SelectedObject.AddForce(Vector3.forward * AddedForce);
SelectedObject.AddTorque (Vector3.up * AddedTorque);
}
When your mouse isn't over an object or the object doesn't have a rigidbody SelectedObject will be initially null. I've also edited my example above and added the else part to reset the selection if you click beside an object or the last one will be selected until you select another one.
Now it gives me the following error at runtime when i click my mouse:
NullReferenceException UnityEngine.Rigidbody.AddForce (Vector3 force) (at C:/BuildAgent/work/f724c1acfee760b6/Runtime/ExportGenerated/Editor/NewDynamics.cs:491) Push.Update ()
Your answer
Follow this Question
Related Questions
raycast hit add force problem, help needed please 1 Answer
Rigidbody.position causes shaking 1 Answer
Can't use Rigidbody.AddForce to RaycastHit.point 1 Answer
overloaded Raycast 0 Answers
RaycastHit behind object 2 Answers