타이머에 맞춰 생성하기
Coddy Unity 여정의 Unity 스크립팅 기초 섹션에 포함된 레슨. 85개 중 63번째.
몇 초마다 무언가를 만드는 생성기에는 타이머가 필요합니다. Time.deltaTime은 마지막 프레임에 걸린 시간이므로, 매 Update()마다 필드에 더하면 경과한 시간이 초 단위로 누적됩니다. 총 시간이 간격에 도달하면 생성하고, 총 시간에서 간격을 빼세요.
이 분수는 0.5초마다 물방울을 하나씩 던집니다.
public GameObject dropPrefab;
public float interval = 0.5f;
float timer;
void Update()
{
timer += Time.deltaTime;
if (timer >= interval)
{
Instantiate(dropPrefab, transform.position, Quaternion.identity);
timer -= interval;
}
}timer -= interval은 남은 시간을 유지합니다. 프레임이 0.51초에 끝났다면 다음 0.5초는 0.01초부터 세기 시작하므로 물방울이 일정한 박자에 맞춰 떨어집니다. timer = 0을 사용하면 남은 시간이 사라져 물방울이 매번 조금씩 늦게 떨어지고, 게임이 오래 진행될수록 지연이 누적됩니다. 인스펙터에서 timer를 설정할 사람이 없으므로 timer는 비공개입니다.
챌린지
중급Inspector에서 interval초마다 상자를 떨어뜨리세요(2초).
float timer;와int count;필드를 추가하세요.Update()에서Time.deltaTime을timer에 더하세요.timer >= interval일 때Instantiate(boxPrefab, transform.position, Quaternion.identity);를 호출하고timer에서interval을 빼세요.- 그런 다음
count에 1을 더하고"Box " + count를 로그에 기록하세요.
‘플레이’를 누르세요. 상자가 2초마다 떨어지고 Console에 Box 1, Box 2가 표시됩니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
using UnityEngine;
public class BoxDropper : MonoBehaviour
{
public GameObject boxPrefab;
public float interval = 1f;
void Update()
{
// interval초마다 상자를 떨어뜨리고 "Box 1", "Box 2"를 차례로 로그에 기록...
}
}
Unity 스크립팅 기초의 모든 레슨
직접 연습해 보세요: Unity 플레이그라운드