상세 컨텐츠

본문 제목

유니티 하이어라키 오브젝트 부모 자식 옮기기

유니티/기능

by MJ_119 2024. 8. 31. 21:18

본문

하이어라키에서 한 오브젝트를 다른 오브젝트의 자식으로 옮기는 코드

 

반드시 오브젝트의 transform을 사용해서 옮겨야함.

using UnityEngine;

public class Enemy : MonoBehaviour
{
    [SerializeField] GameObject collisionVFX;
    [SerializeField] Transform parent2;

    void OnParticleCollision(GameObject other)
    {
        GameObject gg = Instantiate(collisionVFX, transform.position, Quaternion.identity);
        gg.transform.parent = parent2;
    }
}

예시 : 파티클에 충돌했을때 오브젝트의 계층을 옮김.

 

다른방법

using UnityEngine;

public class MakeChild : MonoBehaviour
{
    // 자식으로 만들 오브젝트
    public GameObject childObject;

    // 부모 오브젝트
    public GameObject parentObject;

    void Start()
    {
        // 자식 오브젝트의 부모를 설정
        childObject.transform.SetParent(parentObject.transform);
        
        // 자식 오브젝트의 위치를 부모 오브젝트의 로컬 좌표계로 초기화하고 싶다면 이렇게 할 수 있습니다:
        childObject.transform.localPosition = Vector3.zero;
        childObject.transform.localRotation = Quaternion.identity;
        childObject.transform.localScale = Vector3.one;
    }
}

 

 

 

유니티에서는 gameObject.transform.SetParent()를 사용하는것을 추천함.

using UnityEngine;

public class Enemy : MonoBehaviour
{
    [SerializeField] GameObject collisionVFX;
    [SerializeField] GameObject parent;
    [SerializeField] Transform parent2;

    void OnParticleCollision(GameObject other)
    {
        GameObject gg = Instantiate(collisionVFX, transform.position, Quaternion.identity);
        
        // 방법1
        gg.transform.parent = parent2;
        
        // 방법2
        gg.transform.SetParent(parent.transform);
    }
}

관련글 더보기