So I’ve been trying to parent an object to my player to be able to pull it. The pushing bit was obviously extremely easy.
Yet the things I tried to pull with seemed to not work.
So I have an empty script call MovableBox which I attached to my box I want to move and called it in my colliders
if(collision.gameObject.GetComponent< MovableBox> () != null){canDrag = true; }
And I want to be able to grab box with control
if(Input.GetKey (KeyCode.LeftControl )&& canDrag == true){ }
Now what I used initially was along the lines of transform.parent = this transform.
But I failed to reference the movablebox properly since it didn’t work at all.
Yes I am fairly new, but would appreciate some help.
There are many ways to do this, but for the way you approach it (parenting the player to the box), the first step is to access to object you will move:
MovableBox movableBox = collision.gameObject.GetComponent<MovableBox>();
if (movableBox != null) {
canDrag = true;
movableBox.transform.parent = transform;
}
However, I would go about it very differently: instead of having a canDrag
variable and making the movableBox a child, just store if you collided with a movable box (in a MovableBox variable), and if you are holding ctrl and you have a MovableBox, then any movement vector should also be applied to the movable box as well (you will probably want to make the MovableBox’s rigidbody kinematic).
Btw, transform
and this.transform
are the same thing, so saying transform.parent = this.transform;
is like Darth Vader saying “Luke, YOU are your father”, which doesn’t make sense (it might even give you an error).