- Home /
Question by
HammockHead · Dec 13, 2012 at 03:58 AM ·
rigidbodynullreferenceexceptiondragthrow
Need Help!
I have created a script to allow my FPS Character to pick up objects and through them (like in Amnesia). I can pick up an object and throw it but once I do my Character can no longer pick up objects and i get a NullReferenceException. Also the object is locked on the y axis for some reason.
var baseForce : float = 5; //Base Force Applied to Object
var catchRange : float = 4; //Max Range of Object Interaction
var heldRange : float = 3; //Distance of Object Away from FPS Controller
enum ObjectState { Free, Held, Thrown }; // Free - Can Pick Up, Held - Can Not Pick Up, Thrown - Apply Force to Object
private var objectState : ObjectState = 0; //Set objectStae to Free
private var rigid : Rigidbody = null; //Set var Rigid as unknown
function FixedUpdate() {
if ( objectState == ObjectState.Free ) { //If Free
if (Input.GetButton( "Fire1" )) { //If Fire1 Clicked
var hit :RaycastHit;
if ( Physics.Raycast(transform.position, transform.forward, hit, catchRange )) { //Send Ray Foward by catchRange
if ( hit.rigidbody ) { //If it Hits Rigidbody
rigid = hit.rigidbody;
objectState = ObjectState.Held; //Set objectState to Held
}
}
}
else {
rigid.useGravity = true;
}
}
else if ( objectState == ObjectState.Held ) {
rigid.MovePosition(transform.position + transform.forward * heldRange); //Moves Rigidbody Forward
rigid.useGravity = false; // Disables Gravity
if (Input.GetButton( "Fire2" )) {
rigid.useGravity = true;
objectState = ObjectState.Thrown;
}
}
else if ( objectState == ObjectState.Thrown ) {
rigid.AddForce (transform.forward * baseForce );
objectState = ObjectState.Free;
}
if (!Input.GetButton( "Fire1" )) {
objectState = ObjectState.Free;
}
}
Comment
does the rigidbody act how you want until you try to pick it up? the second time that is?
Your answer
Follow this Question
Related Questions
Drag and throw Rigidbody2d? 3 Answers
Can I have a rigidbody continue to calculate physics while being dragged by code? 2 Answers
Limiting the top speed of a rigidbody in 3d space? 1 Answer
Drag around riggidbodies with a "pin" 0 Answers
How to move a group of objects with rigidbodies together? 2 Answers