- Home /
How to pull object with this code setup?
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.
Answer by Harinezumi · Apr 24, 2018 at 03:13 PM
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).
Yeah, I am still having trouble for some reason.
I'll try and figure it out.
But would you be as kind to elaborate on your suggested method a little bit?
The particular problem I still have is a nullReferenceException
Your answer
Follow this Question
Related Questions
Pulling in another object 1 Answer
adding Up force 0 Answers
Touch Detection in 2D Game 3 Answers
Add a force at an angle 1 Answer
Unity 4.3.4 2D mode, hide mouse pointer only works on half of the screen 0 Answers