2
\$\begingroup\$

I modified a grab Script to my purpose, I can grab the Object and make it a parent to the character with the Key "G" but I want to let it go and detach the parent of the picked Object with "H" with the Code: "hit.transform.parent = null;" but i cant get it to work, I dont know where to put it.

Code:


[SerializeField]
private Transform RayCastGrab;
[SerializeField]
private float raySize;
private Transform pickUpObj;
private Vector3 lastPos;

public LayerMask GrabLayer;

void Update () 
{
    PickRayLayer();
}

void PickRayLayer()
{
    Ray rayF = new Ray (RayCastGrab.position, transform.forward);
    Debug.DrawRay(rayF.origin, rayF.direction * raySize, Color.black);

    RaycastHit hit;

    if(Input.GetKey (KeyCode.G))
    {   

        if (Physics.Raycast(rayF, out hit, 2f, GrabLayer))
        {
            //Picking up the Object and make it a parent of Player
            pickUpObj = hit.transform;
            hit.transform.parent = this.transform;
        }
    }

    if(Input.GetKey (KeyCode.H))
    {
        //Should let the grabbed Object go and detach it from parent of Player
        if(pickUpObj)
            pickUpObj = null;
        transform.parent = null;
    }

    if(pickUpObj)
    {
        pickUpObj.transform.position += transform.position - lastPos;
    }
\$\endgroup\$
1
\$\begingroup\$

Since you saved the Transform of the object you picked up in the variable pickUpObj, it looks like you want:

if(Input.GetKeyDown(KeyCode.H))
{
     if(pickUpObj != null) {
         pickUpObj.parent = null;
         pickUpObj = null;
     }
}
\$\endgroup\$
  • \$\begingroup\$ I dont know why but this is still not working however, it is not letting the GameObjet go or neither detach the Object from Player.. \$\endgroup\$ – Daniel Feb 8 '18 at 5:09
  • \$\begingroup\$ It looks like you're positioning the object both via parenting and by continually updating its position. That looks unusual, so I'd check if that later portion is still having an effect. Also, if the object has a Rigidbody, just parenting it won't give the desired effect, and you may want to pin it in place with a joint instead. \$\endgroup\$ – DMGregory Feb 8 '18 at 5:12
  • \$\begingroup\$ I parented the Object because I wanted the Object rotates with the player, that was my only idea of doing it the "easy way" but now the problem is to detach the object when pressing "H", but I dont know what to do now. \$\endgroup\$ – Daniel Feb 8 '18 at 5:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.