Ray ray = new Ray(RayOrigin.transform.position, RayOrigin.transform.forward);
RaycastHit hit;
if (Input.GetMouseButtonDown(0) && Physics.Raycast(ray, out hit, 20f) && hit.collider.gameObject.CompareTag("Pickable"))
{
hit.rigidbody.constraints = RigidbodyConstraints.FreezeAll;
}
if (Input.GetMouseButtonUp(0))
{
hit.rigidbody.constraints = RigidbodyConstraints.None;
}
I keep getting this error: “use of unassigned local variable ‘hit’”. How do I fix this?
On line 11 hit won’t have a value, but you’re still trying to access it. What are you trying to do?
Essentially when the left mouse button is down (pressed) freeze the rigid body constraints and when I let go remove all constraints. I’m assuming I need to log/store the rigid body somehow? I guess…
Well I got what I wanted to work… kind of… It now freezes the constraints on LMB press and then releases them when the LMB is released. Problem is the release portion (when the LMB is released) relies on a raycast and it doesn’t always hit (depending on where the player is looking). There must be a better way.
Current Code…
Ray ray = new Ray(RayOrigin.transform.position, RayOrigin.transform.forward);
RaycastHit hit;
if (Input.GetMouseButtonDown(0) && Physics.Raycast(ray, out hit, 20f) && hit.collider.gameObject.CompareTag("Pickable"))
{
hit.rigidbody.constraints = RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
}
if (Input.GetMouseButtonUp(0) && Physics.Raycast(ray, out hit, 20f) && hit.collider.gameObject.CompareTag("Pickable"))
{
hit.rigidbody.constraints = RigidbodyConstraints.None;
}
Store the rigidbody you hit pressing down in a class variable. Then release from this instead of ratcheting again.