Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Attach One Object to Another

Discussion in '2D' started by SheldonS, Sep 3, 2015.

  1. SheldonS

    SheldonS

    Joined:
    Jul 23, 2015
    Posts:
    21
    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?
     
  2. Dave_Voyles

    Dave_Voyles

    Joined:
    Feb 7, 2014
    Posts:
    32
  3. SheldonS

    SheldonS

    Joined:
    Jul 23, 2015
    Posts:
    21
    I was thinking about at run time using C#.
     
  4. SheldonS

    SheldonS

    Joined:
    Jul 23, 2015
    Posts:
    21
    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.
     
  5. Dave_Voyles

    Dave_Voyles

    Joined:
    Feb 7, 2014
    Posts:
    32
    Is it working now?

    The trick is using the same script for both objects.
     
    theANMATOR2b likes this.
  6. SheldonS

    SheldonS

    Joined:
    Jul 23, 2015
    Posts:
    21
    Yep.

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

    Code (CSharp):
    1.     void FixedUpdate()
    2.     {
    3.         float v = Input.GetAxisRaw(yAxis);
    4.         GetComponent<Rigidbody2D>().velocity = new Vector2(0, v) * speed;
    5.         foreach (Transform oChild in transform)
    6.         {
    7.             oChild.GetComponent<Rigidbody2D>().velocity = new Vector2(0, v) * speed;
    8.         }
    9.     }
     
    Dave_Voyles likes this.