Saturday, August 18, 2018

unity - How to refer to a object that has just been hit by a ray cast?



I would like to use RigidbodyConstraints.FreezeRotation;in order to freeze the rotation of an object that is picked up. The problem is I don't know how to refer (or call) the currently selected object. The script in it's currents state is below...


public class PhysGun : MonoBehaviour
{
private GameObject Player;

void Start ()
{
Player = GameObject.Find("Player");
}


// Update is called once per frame
void Update ()
{
Vector3 fwd = transform.forward; // Equivalent to the code you had.

Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;

if (Input.GetMouseButton(0) && Physics.Raycast(ray, out hit, 10f))
{

hit.transform.SetParent(Player.transform);
Debug.Log("We hit: " + hit.transform.name);
hit.transform. = RigidbodyConstraints.FreezeRotation;
}

}

}

So, how do I call (or refer to) the object that is hit by the ray cast exactly?




Answer



Rigidbody Contraints is a class to use for the rigidbody. In your case, instead of using hit.transform. = RigidbodyConstraints.FreezeRotation;, I would replace that with hit.GetComponent().constraints = RigidbodyConstraints.FreezeRotation;
I see that you have tried to set a Rigidbody class on a Transform. Rigidbody constraints take a RigidbodyConstraints class, as said in the docs here. As I would guess, the source code might look similar to this:


public class Rigidbody {
...
[SerializeField]
public RigidbodyConstraints constraints;
...
}


The docs for the RigidbodyConstraints class is here.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...