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

Question SetSiblingIndex causing unwanted shuffling of child objects in hierarchy

Discussion in 'Scripting' started by AASCENDED, May 3, 2022.

  1. AASCENDED

    AASCENDED

    Joined:
    Nov 18, 2018
    Posts:
    6
    I am writing code for my weapon system, which allows the player to equip 4 weapons at one time (which are each child objects of a WeaponHolder object), the player is able to drop the weapons and the slot becomes empty. The issue I am running into is when the player drops weapon in child index 2, and then the weapon in child index 3, it causes unwanted shuffling of other child objects.

    The way my code works is when the player removes a weapon, it destroys the weapon and instantiates an empty object, which gets its sibling index set to the same index the weapon had before it was destroyed. This systems works for the most part (ie. if index 0 is dropped, and then index 1, it functions correctly).

    Code (CSharp):
    1. emptyObj.transform.SetParent(wepHolder.transform);
    2. emptyObj.transform.SetSiblingIndex(wepslotInt);
    Image 1: After dropping the weapon in slot 2 at runtime.
    Image 2: After dropping the weapon in slot 3 at runtime. It should look like RailGun in slot 0, and 1, followed by the 2 empty slots named Slot2 and Slot3.

    Thank you so much for any help.
     

    Attached Files:

  2. Dextozz

    Dextozz

    Joined:
    Apr 8, 2018
    Posts:
    488
    Why are you doing it like this anyway? In my opinion, GetChild() used in almost any context is a code smell. Why are you depending on arbitrary object hierarchy? Why don't you manage the ordering of this through code?
     
  3. AASCENDED

    AASCENDED

    Joined:
    Nov 18, 2018
    Posts:
    6
    I took your advice and just wrote some code to manage my weapon slots through code and it definitely was the route, don't have to deal with the hassle of using sibling indexes.
     
    Dextozz likes this.