Search code examples
c#unity-game-enginegameobject

edit Gamobject with just Collider reference in Unity


i want to pick up a sheep and move it to the players head by parenting it to an empty gameobject. This is all working fine except the sheep not moving to the head but stays in his position while parented. Is there any way to transform the position of the sheep with just it's collider reference? Sorry if this is a noob question, I'm an beginner and i hope you can help me! Thanks in advance!

if (Input.GetKey(KeyCode.Space)) {
            if (targetTime <= 0.0f)
            {
                targetTime = 2f;
                if (inhand == true)
                {
                    InHand.transform.SetParent(null);
                    inhand = false;
                    Debug.Log("Abgelegt");
                }
                else
                {
                    Collider2D[] sheepsinrange = Physics2D.OverlapCircleAll(attackPos.position, attackRange, whatIsEnemies);
                    if (sheepsinrange.Length > 0)
                    {
                        InHand = sheepsinrange[0];
                        InHand.transform.SetParent(sheepPos);
                        inhand = true;
                        Debug.Log(sheepsinrange + " aufgenommen");
                    }
                }
            }
        }
    }

Solution

  • Its pretty simple, once you've set the parent you just need to reset its local position.

    You can either set it manually InHand.transform.localPosition = vector3.zero; or since your using SetParent() you can use the second parameter -> SetParent(Transform parent, bool worldPositionStays) which by default is true so it stays in the same position. So you want :

    InHand.transform.SetParent(sheepPos, false);