본문 바로가기

프로그래밍 - 기본/CPP, Unity, Kotlin

[C#] GameObject[]에 Text할당하기

1. 문제

GameObject[]를 Text로 표현하는 것이 해결해야 할 과제였다.

GameObject를 Text로 표현하는 것은 굉장히 간단하다. 찾은 것 뒤에 .GetComponent<Text>를 추가하면 되기 때문이다.

하지만 GameObject[]는 이야기가 다르다.

MainInv = GameObject.FindGameObjectsWithTag("MenuInv").GetComponent<Text>;

위와 같이 GetComponent를 추가하면 다음과 같은 error가 발생한다.

'GameObject[]' does not contain a definition for 'GetComponent' and no accessible extension method 'GetComponent' accepting a first argument of type 'GameObject[]' could be found (are you missing a using directive or an assembly reference?)

GameObject를 바로 Text로 표현할 수 없기에, 직접 하나 하나씩 Text를 찾아주기로 결심했다. 즉, GameObject[]의 요소 하나 하나마다 GetComponent<Text>를 적용시키는 방법을 선택했다.

 

2. 해결

private GameObject[] MainInv;
MainInv = GameObject.FindGameObjectsWithTag("MenuInv");
for (int i = 0; i < 8; i++)
        {
            MainInv[i].GetComponent<UnityEngine.UI.Text>().text = "x " + inventory[i];
        }

array형태로 되어 있는 GameObject의 각각 하나씩 text를 찾도록 하였다.

실행하니 error가 뜨지 않고 올바르게 인벤토리가 뜨는 것을 확인하였다!

3. 도움이 되었던 사이트

https://forum.unity.com/threads/getcomponent-for-ui-text.854173/