Search Unity

Question Changing Rigidbody Variable With Raycasting

Discussion in 'Physics' started by blaizeis1, Sep 16, 2020.

  1. blaizeis1

    blaizeis1

    Joined:
    Feb 21, 2020
    Posts:
    1
    Please forgive me but I am a total newbie to Unity and understand very little about C#. Anyway, I have multiple rigidbodies in a scene and am using a raycast function that returns rigidbody info and stores it inside of a variable (Clearly I copy and pasted this from some other post)

    public Rigidbody GetRigidbodyFromMouseClick()
    {
    RaycastHit hitInfo = new RaycastHit();
    Ray ray = targetCamera.ScreenPointToRay(Input.mousePosition);
    bool hit = Physics.Raycast(ray, out hitInfo);
    if (hit)
    {
    if (hitInfo.collider.gameObject.GetComponent<Rigidbody>())
    {
    selectionDistance = Vector3.Distance(ray.origin, hitInfo.point);
    originalScreenTargetPosition = targetCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, selectionDistance));
    originalRigidbodyPos = hitInfo.collider.transform.position;
    return hitInfo.collider.gameObject.GetComponent<Rigidbody>();
    }

    }

    return null;
    }

    This is then utilized with

    if (Input.GetMouseButtonDown(0))
    {
    m_Rigidbody = GetRigidbodyFromMouseClick();
    }

    So in the inspector, the rigidbody variable is populated with the rigidbody that was raycasted; this is what I want. I want to use this to press a button to rotate the selected Rigidbody. I also want this rigidbody to become deselected when anywhere else on the screen is clicked. My problem is that when I press my button, the rigidbody becomes deselected so I cannot use it to rotate my rigidbodies. Am I missing something? Is there a better way around accomplishing what I want?

    Thanks in advance.
     

    Attached Files:

  2. CaseyHofland

    CaseyHofland

    Joined:
    Mar 18, 2016
    Posts:
    613
    First of all, from the code you posted here it seems like you can massively simplify your method:
    Code (CSharp):
    1. var ray = targetCamera.ScreenPointToRay(Input.mousePosition);
    2. if(Physics.Raycast(ray, out var hitInfo))
    3. {
    4.     return hitInfo.rigidbody;
    5. }
    6.  
    7. return null;
    (Don't feel bad, you'll get there too one day.)

    Now for the rest of your issue... I'm didn't understand from your explanation how you would rotate the rigidbody. Like, do you want to use A and D when the rigidbody is selected or something? Could you please elaborate?