Search Unity

2d animation combining sprites

Discussion in 'Scripting' started by gibberingmouther, Sep 19, 2017.

  1. gibberingmouther

    gibberingmouther

    Joined:
    Dec 13, 2016
    Posts:
    259
    so i'm glad i finally have a solution to most of my 2d woes, thanks to Neurological and Diviner. but now i've been thinking about the subsequent steps - is there a way to attach an object, such as a sword or mace or staff, to another object, such as a hero or enemy? how would i even approach this? i'm worried this could be a really big hurdle.

    i can't just animate a guy with a sword - the guy and the sword have to be separate objects because i have so many items.

    i think i had a solution for this in Game Maker, but Unity isn't Game Maker (though it's a lot better).
     
  2. RoMax92

    RoMax92

    Joined:
    May 29, 2017
    Posts:
    135
    You can simply create an empty gameobject as child in the hand of the animation thing and assing the "sword" or other stuff to that gameobject.
    The animation move the hand and the object is dragged as well.
     
    gibberingmouther likes this.
  3. RoMax92

    RoMax92

    Joined:
    May 29, 2017
    Posts:
    135
    When you instantiate the object you have to set the parent as the "hand":
    Code (CSharp):
    1. public swordPrefab;
    2. public handObj;
    3. void Start () {
    4. Gameobject obj = Instantiate(swordPrefab, handObj.transform);
    5. }
    Some documentation: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html

    If you want to destroy the sword in a second moment you can just:
    Code (CSharp):
    1. public swordPrefab;
    2. public handObj;
    3. private Gameobject objSword;
    4.  
    5. void Start () {
    6. objSword = Instantiate(swordPrefab, handObj.transform);
    7. }
    8.  
    9. void DestroySword () {
    10. Destroy(objSword);
    11. }
     
    gibberingmouther likes this.
  4. gibberingmouther

    gibberingmouther

    Joined:
    Dec 13, 2016
    Posts:
    259
    the parent is an entire body - is this still doable? can i change where in respect to the parent transform the object is, from frame to frame?

    edit: it looks like i can use
    Code (csharp):
    1.  
    2. public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
    3.  
    am i correct?
     
    Last edited: Sep 21, 2017
  5. RoMax92

    RoMax92

    Joined:
    May 29, 2017
    Posts:
    135
    If is a 2D game you can write only the object and the transform parent

    Do you have an animation alredy? Add an empty gameobject called "hand" in the player and anime it in the animation as you want. When you assign the item to the hand, the item follow the hand animation