Attach One Object to Another

I have been working on a game to teach myself Unity 2D games. One thing I am trying to figure out is how to attach one game object to another and have them move together. This is in a 2D setting. I have tried the SetParent as I see recommended in numerous places but it is not moving the newly attached object.

Since I instantiate one object and have it “float” down I use its OnCollision event to set the parent and thus attach it to the player. I still want to use the attached object for different things in the future; destroy it, have it as a source to shoot etc…

Does anyone know of a good tutorial or article that might help me get past this point?

You can create a parent object, and then create a child object, and attach the two by dragging the child on top of the parent from within the inspector window.

This article explains it well: http://unity3d.com/learn/tutorials/modules/beginner/editor/the-hierarchy-and-parent-child-relationships

I was thinking about at run time using C#.

I believe I was thinking of the parent/child thing a bit wrong. I thought that if I made one item the child of another they would still move together. Maybe that is true if you use a controller, I was moving the parent in the FixedUpdate accessing the Vertical axis.

In code I did set the parent. I could see it and log it to the console. They just were not moving together. So I added the same basic move method to the child’s FixedUpdate. Tada! They move together.

Is it working now?

The trick is using the same script for both objects.

1 Like

Yep.

The SetParent works as expected. I changed my player’s FixedUpdate to also move any children.

    void FixedUpdate()
    {
        float v = Input.GetAxisRaw(yAxis);
        GetComponent<Rigidbody2D>().velocity = new Vector2(0, v) * speed;
        foreach (Transform oChild in transform)
        {
            oChild.GetComponent<Rigidbody2D>().velocity = new Vector2(0, v) * speed;
        }
    }
1 Like