GSI

Button을 Prefab로 등록한후 게임상에서 환경에 따라서 Button을 여러개 생성해야할 경우가 생긴다.

부모가 되는 GameObject의 Transform 객체 하부로 연결하면 된다.


> GameController 는 Main Camera 에 스크립트로 등록한다.

> uiRoot는 UI의 최상의 Canvas 객체이다.

> tileButton는 Prefab로 등록되어 있는 버튼 객체이다.


Start() 함수에서

Instantiate (tileButton); 이 코드만 실행하면 Root의 자식으로 생기기 때문에 

원래 의도한 Canvas의 자식으로 생성되지 않는다.

아래와 같은 코드로 하게 되면 자식으로 등록이 된다.


-- 코드 --

using UnityEngine;

using UnityEngine.UI;

using System.Collections;


public class GameController : MonoBehaviour {


public GameObject uiRoot;

public Button tileButton;


// Use this for initialization

void Start () {

Button child = Instantiate (tileButton);

child.transform.parent = uiRoot.transform;

}

// Update is called once per frame

void Update () {

}

}


하지만 위와 같이 하면 동작은 되지만 아래와 같은 메시지가 뜨게 된다.

Parent of RectTransform is being set with parent property. Consider using the SetParent method instead, with the worldPositionStays argument set to false. This will retain local orientation and scale rather than world orientation and scale, which can prevent common UI scaling issues.


이 경우 SetParent()를 사용하면 된다.


child.transform.parent = uiRoot.transform;

child.transform.SetParent (uiRoot.transform);

Posted by gsi
: