Unity로 간단한 프로젝트를 친구들과 진행 중인데, 진행하면서 배운 것들 중 기록할만한 것들을 기록하려고 한다.
Unity를 사용하다 보면 다른 오브젝트에 붙어 있는 스크립트 내부의 변수나 배열을 가져와 사용해야 할 경우가 있다.
내 경우에서는 ControlManager를 따로 두고 해당 스크립트에 사용할 변수와 배열을 생성해두고 다른 스크립트에서 수정하거나 값을 가져와서 사용했다.
먼저 다른 스크립트에서 사용하려면 아래와 같이 public 으로 함수를 생성해주어야 한다.
그래야 외부에서 참조가 가능해진다.
using UnityEngine;
public class ControlManager : MonoBehaviour
{
private int[] _ControlArray = new int[5];
private int _ControlIndex = 0;
// ControlArray를 가져오는 함수
public int[] GetControlArray()
{
return _ControlArray;
}
// ControlArray를 외부에서 수정하기 위한 함수
public void SetControlArray(int index, int type)
{
_ControlArray[index] = type;
}
// ControlIndex를 가져오는 함수
public int GetControlIndex()
{
return _ControlIndex;
}
// ControlIndex를 외부에서 수정하는 함수
public void SetControlIndex(int index)
{
_ControlIndex = index;
}
위와 같이 코드를 작성한 다음 Unity에 Hierarchy를 우클릭해 Create Empty를 통해 ControlManager 이름의 빈 오브젝트를 생성한 뒤에 해당 스크립트를 넣어 주었다.
그 뒤 참조하고 싶은 다른 스크립트에서 해당 함수를 사용하면 된다.
아래와 같이 코드를 작성하면 ControlManager 오브젝트 내부의 스크립트에 있는 함수를 사용할 수 있게 되어, 외부 스크립트의 변수나 배열까지 불러와 사용할 수 있다.
using UnityEngine;
using UnityEngine.UI;
public class BtnSetting : MonoBehaviour
{
private ControlManager controlManager;
private void SetControlArray()
{
// ControlManager 오브젝트 안에 ControlManager 스크립트를 가져온다.
controlManager = GameObject.Find("ControlManager").GetComponent<ControlManager>();
// ControlManager 내부의 ControlArray 배열을 가져와 array에 초기화
int[] array = controlManager.GetControlArray();
// ControlManager 내부의 ControlIndex 변수를 가져와 idx에 초기화
int idx = controlManager.GetControlIndex();
}
}
기록용으로 작성하는 것이기도 하고, 처음 작성해보는 것이라 내용이 많이 부족한 듯한데, 그래도 이 글을 찾아온 사람들에게 도움이 되었으면 좋겠다.