람다
Coddy Unity 여정의 실제 게임 만들기 섹션에 포함된 레슨. 60개 중 7번째.
AddListener는 매개변수가 없는 메서드를 받습니다. 클릭할 때 색상을 받는 Paint(Color.red)를 호출하려면, 메서드를 그 자리에서 작성하세요: () => Paint(Color.red). 이것은 이름이 없는 메서드인 람다입니다. ()에는 매개변수가 들어가며, 여기에는 매개변수가 없습니다. => 뒤에는 본문이 옵니다. 문 하나 또는 여러 문을 위한 { } 블록입니다:
public Button redButton;
public Button blueButton;
public Button resetButton;
public Renderer lamp;
private int changes;
void Start()
{
redButton.onClick.AddListener(() => Paint(Color.red));
blueButton.onClick.AddListener(() => Paint(Color.blue));
resetButton.onClick.AddListener(() =>
{
changes = 0;
lamp.material.color = Color.white;
});
}
void Paint(Color color)
{
lamp.material.color = color;
changes++;
}하나의 Paint 메서드가 두 색상 버튼에서 모두 사용되며, 각 람다는 각자의 색상을 전달합니다. 람다는 사용하는 변수를 캡처합니다. 변수의 값을 복사하는 것이 아니라, 실행될 때 그 값을 읽습니다. 재설정 람다는 클릭할 때마다 필드 changes를 설정하며, 이는 Start()가 끝난 뒤 한참 후에도 마찬가지입니다.
반복문에서는 문제가 생길 수 있습니다. swatches[i].onClick.AddListener(() => Paint(colors[i]));에서는 모든 람다가 같은 i를 캡처하며, 누군가 클릭할 즈음에는 반복문이 끝나 i가 colors.Length와 같아집니다. 그러면 모든 견본에서 IndexOutOfRangeException이 발생합니다. 반복문 안에서 선언한 변수는 반복할 때마다 새로 만들어지므로, i를 그 변수에 복사하고 복사본을 캡처하세요:
for (int i = 0; i < swatches.Length; i++)
{
int index = i;
swatches[i].onClick.AddListener(() => Paint(colors[index]));
}챌린지
쉬움Start()에서 금고의 키패드를 연결하세요.
for를 사용해keys를 반복하세요. 반복문 안에서int digit = i + 1;을 선언하고keys[i]를() => Press(digit)에 연결하세요.clearButton을entered = ""을 설정하고ShowCode()를 호출하는 하나의 람다에 연결하세요.
‘플레이’를 누르고 3, 1, 2를 입력하세요. 화면에 Open이라고 표시됩니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Keypad : MonoBehaviour
{
public Button[] keys;
public Button clearButton;
public TMP_Text codeText;
public GameObject door;
public string secret = "312";
private string entered = "";
void Start()
{
ShowCode();
// 각 키를 해당 숫자와 함께 Press에 연결하고, clearButton은 코드를 지우는 기능에 연결합니다
}
void Press(int digit)
{
entered += digit;
ShowCode();
if (entered.Length == 3)
{
if (entered == secret)
{
door.SetActive(false);
codeText.text = "Open";
}
else
{
codeText.text = "Wrong";
}
entered = "";
}
}
void ShowCode()
{
codeText.text = "Code: " + entered;
}
}
실제 게임 만들기의 모든 레슨
직접 연습해 보세요: Unity 플레이그라운드