profile image

L o a d i n g . . .

article thumbnail image
Published 2020. 9. 24. 03:03
반응형

Coroutine

길 찾기 등 오래 걸리는 로직이라면 여러 프레임에 거쳐서 처리하는 게 나을 수도 있다.

함수를 일시정지를 했다가 다음 Tick에 해당 작업을 이어서 수행할 수 있게끔 한다.

class CoroutineTest : IEnumerable
{
    public IEnumerator GetEnumerator()
    {
        yield return 1;
        yield return 2;
        yield return 3;
        yield return 4;
    }
}

protected override void Init()
{
    base.Init();

    SceneType = Define.Scene.Game;

    Managers.UI.ShowSceneUI<UI_Inven>();

    CoroutineTest test = new CoroutineTest();
    foreach(int t in test)
    {
        Debug.Log(t);
    }
}

 

코루틴 함수를 완전 종료할 때는 yield break; 를 사용한다.

 

1. 함수의 상태를 저장/복원 가능
=> 엄청 오래 걸리는 작업을 잠시 끊거나, 원하는 타이밍에 함수를 잠시 Stop/복원하는 경우

2. return => 우리가 원하는 타입으로 가능(class도 가능)

4초 후에 터지는 스킬 등, 시간 관리에도 큰 이점이 있다.

 

protected override void Init()
{
    base.Init();

    SceneType = Define.Scene.Game;

    Managers.UI.ShowSceneUI<UI_Inven>();

    StartCoroutine("ExplodeAfterSeconds", 4.0f);
}

IEnumerator ExplodeAfterSeconds(float seconds)
{
    Debug.Log("Explode Enter");
    yield return new WaitForSeconds(seconds);
    Debug.Log("Explode Execute!!!");
}

 

StopCoroutine()을 이용하면 코루틴을 중단할 수 있다.

 

 

Data

세이브/로드 개념보다는 게임에 존재하는 모든 수치들을 관리한다.

JSON or XML 파일로 관리한다. 

 

{
  "stats": [
    {
      "level": "1",
      "hp": "100",
      "attack": "10"
    },
    {
      "level": "2",
      "hp": "150",
      "attack": "15"
    },
    {
      "level": "3",
      "hp": "200",
      "attack": "20"
    }
  ]
}

 

JSON 파일 데이터를 TextAsset으로 불러온다.

public void Init()
{
    TextAsset textAsset = Managers.Resource.Load<TextAsset>($"Data/StatData");
    Debug.Log(textAsset.text);
}

 

[Serializable]: 파일로 변환할 수 있음을 명시한다. 데이터들을 public으로 선언해 주거나, private로 유지하고 싶은 경우에는 [SerializeField]를 붙인다.

Unity에서는 원활한 JSON Parsing을 위한 JsonUtility를 제공한다.

 

타입명과 변수명은 맞춰 줘야 함에 주의한다!

[Serializable]
public class Stat
{
    public int level;
    public int hp;
    public int attack;
}

[Serializable]
public class StatData
{
    public List<Stat> stats = new List<Stat>();
}

public class DataManager
{
    public Dictionary<int, Stat> StatDict { get; private set; } = new Dictionary<int, Stat>();

    public void Init()
    {
        TextAsset textAsset = Managers.Resource.Load<TextAsset>($"Data/StatData");
        StatData data = JsonUtility.FromJson<StatData>(textAsset.text);

        foreach (Stat stat in data.stats)
            StatDict.Add(stat.level, stat);
    }
}
반응형
복사했습니다!