개발괴발 공부
n초마다 배열에 있는 원소 값 불러오기
방프
2021. 4. 26. 22:33
// 2초마다 배열에 있는 원소 값을 불러오기
// 1. InvokeRepeating사용
void Start()
{
InvokeRepeating("Repeat", 0, 2);
}
void Repeat()
{
if (index >= position.Length)
index = 0;
Debug.Log(position[index]);
index++;
}
// 2. 코루틴 사용
private void Start()
{
StartCoroutine(Repeat(0));
}
IEnumerator Repeat(int _index)
{
Debug.Log(position[_index]);
yield return new WaitForSeconds(2);
_index++;
if (_index >= position.Length)
_index = 0;
StartCoroutine(Repeat(_index));
}
// 3. Update함수 사용
private void Update()
{
time += Time.deltaTime;
if(time >= 2.0f)
{
if (index >= position.Length)
index = 0;
Debug.Log(position[index]);
index++;
time = 0;
}
}
// 4. Update함수 사용2 (모듈러 연산자 사용)
private void Update()
{
time += Time.deltaTime;
if(time >= 2.0f)
{
Debug.Log(position[index2 % (position.Length)]);
index2++;
time = 0;
}
}
// 4번은 3번의 세 문장을
if (index >= position.Length)
index = 0;
Debug.Log(position[index]);
// 아래의 한 문장으로 만들 수 있다.
Debug.Log(position[index2 % (position.Length)]);