본문 바로가기
게임개발

[Unity] Transform.SetParent

by 개발도사(진) 2023. 1. 19.

1. 프리팹을 Resources.Load()로 불러 온 다음에 바로 부모-자식 관계를 설정하려고 하면 에러가 난다. 

(error: Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption)

 

GameObject prefab = Resources.Load("Prefabs/xxx") as GameObject;
GameObject prefabInstance = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
prefabInstance.SetParent(parent.transform);

와 같이, 인스턴스화를 한 후에 SetParnet를 해 줘야 한다.

 

2. SetParent(parent.transform, false)

내 목표는 Panel 안에(엄밀하게는 버튼들을 정렬하기 위한 Grid Layout Group Component를 가지고 있는 Empty Object 의 자식으로) 버튼들을 추가해주는 것이었다. 그런데 스크립트를 통해 버튼을 생성하고, SetParent(parent.transform)을 통해 버튼을 하위오브젝트로 넣어 주었을 때는 버튼들이 죄다 겹쳐서 생성되는 문제가 발생했다.

 

이유인즉슨 이 함수가

public void SetParent (Transform parent, bool worldPositionStays);

로 overloading 되어 있는데, worldPositionStays가 true이면 자식이 되는 오브젝트의 월드 좌표가 변경되지 않기 때문이다.

 

buttonInstance.transform.SetParent(parent.SetParent,false);

코드를 사용했을 때, 의도대로 버튼들이 생성되어 정렬되었다. 

'게임개발' 카테고리의 다른 글

[Unity] 추적 카메라  (0) 2023.01.03
[Unity] UI_Canvas  (0) 2023.01.03
[Unity] Physics.Raycast  (0) 2023.01.01
[Unity] Collider  (0) 2023.01.01
[문제] Transparency Sort Axis가 Play mode 실행 시 원래대로 돌아가는 문제  (0) 2022.09.15