Unity 2017.1 부터 .Net 4.x 스크립팅 런타임(Scripting Runtime)을 사용가능하게 되면서 C#의 새로운 기능들을 유니티에서도 사용할 수 있게되었다.
https://docs.microsoft.com/ko-kr/visualstudio/cross-platform/unity-scripting-upgrade?view=vs-2019
새로운 기능들은 하나하나가 달달한 syntax sugar가 되어 코딩을 달게 만들어준다.
가장 단것은Null 조건부 연산자.
// .Net 3.5
if(var == null) foo.bar();
// .Net 4.x
foo?.bar();
. 이나 [] 앞에 ?를 붙이면, 오브젝트가 Null인지 아닌지를 먼저 판별하여 Null이면 이후 코드를 실행하지 않는다.
Action action = null;
// .net 3.5
if (action != null)
action();
// .net 4.x
action?.Invoke();
delegate에도 적용가능하다.
그 다음은 async/await를 이용한 TAP이 가장 많은 코드를 줄여주고 코루틴과 콜백의 악몽에서 우리를 구해준다.
using UnityEngine;
public class UnityCoroutineExample : MonoBehaviour
{
private string result;
private void Start()
{
StartCoroutine(WaitOneSecond());
DoMoreStuff(); // This executes without waiting for WaitOneSecond
}
private IEnumerator WaitOneSecond()
{
yield return new WaitForSeconds(1.0f);
result = "result";
StartCoroutine(DoCallback());
}
}
코루틴이 코루틴을 실행시키고 코루틴 중간 계산값은 멤버로 저장해야하고 정말 끔찍한 코드를 만들어내는 주범 중 하나였던 코루틴을
// .NET 4.x async-await
using UnityEngine;
using System.Threading.Tasks;
public class AsyncAwaitExample : MonoBehaviour
{
private async void Start()
{
string result = await WaitOneSecondAsync();
await DoCallBack(result);
}
private async Task<string> WaitOneSecondAsync()
{
await Task.Delay(TimeSpan.FromSeconds(1));
return "result";
}
}
결과값을 받아와 콜백을 바깥에서 처리 할 수있기 때문에 태스크를 사용하면 한결 깔끔하게 작성할 수 있다. async/await의 활용 방안은 여기 다룰수 없을만큼 많기에 생략한다.
이외에는 문자열 포맷팅에 성능도 좋고 깔끔한 코드를 제공하는 문자열 보간,
// .NET 3.5
Debug.Log(String.Format("Player health: {0}", Health)); // or
Debug.Log("Player health: " + Health);
// .NET 4.x
Debug.Log($"Player health: {Health}");
함수와 프로퍼티를 람다식처럼 사용할 수 있는 식 본문 멤버가 있다. (나는 좋아하는데 팀원들이 싫어하더라 ㅠ)
// .NET 3.5
private int TakeDamage(int amount)
{
return Health -= amount;
}
// .NET 4.x
private int TakeDamage(int amount) => Health -= amount;
.Net 4.x를 사용한다면 어플리케이션 용량이 약간 증가 할 수 있으니, 구글플레이의 OBB를 넣어야하는 100mb 제한에 간당간당한 게임들은 이 기회에 OBB를 지원하는 것이 좋다. 왜냐하면 .Net 4.x가 너무 좋기 때문에...
'Unity' 카테고리의 다른 글
Unity 개발자가 Rider를 사용해야 하는 이유 (Rider 장점) (2) | 2020.02.11 |
---|