반응형
2.5.5 for문으로 반복하기
- 반복 횟수를 지정하면 자동으로 반복 횟수만큼 처리를 반복하는 for문을 사용
for (반복 횟수)
{
처리
}
for (변수 초기화; 반복 조건식; 변수 갱신)
{
처리
}
① i 변수를 0으로 초기화
② 반복 조건(i < 5)을 만족하면 ③, 만족하지 않으면 반복문을 종료
③ Console 창에 i 값을 출력
④ i를 증가시킴 (i 값을 1 증가)
⑤ ②로 돌아감
※ for 문 사용하기
using System.Collections;
using System.Collections.Generic;
using UnityEngine; // 유니티가 동작하는데 필요한 기능 제공
public class test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < 5; i++)
{
Debug.Log(i);
}
}
}
결과값 보기
더보기
0
1
2
3
4
※ 짝수만 출력하기
using System.Collections;
using System.Collections.Generic;
using UnityEngine; // 유니티가 동작하는데 필요한 기능 제공
public class test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < 10; i += 2)
{
Debug.Log(i);
}
}
}
결과값 보기
더보기
0
2
4
6
8
※ 특정 범위만 출력하기
using System.Collections;
using System.Collections.Generic;
using UnityEngine; // 유니티가 동작하는데 필요한 기능 제공
public class test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
for (int i = 3; i <= 5; i++)
{
Debug.Log(i);
}
}
}
결과값 보기
더보기
3
4
5
※ 카운트다운하기
using System.Collections;
using System.Collections.Generic;
using UnityEngine; // 유니티가 동작하는데 필요한 기능 제공
public class test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
for (int i = 3; i >= 0; i--)
{
Debug.Log(i);
}
}
}
결과값 보기
더보기
3
2
1
0
※ 합계 구하기
using System.Collections;
using System.Collections.Generic;
using UnityEngine; // 유니티가 동작하는데 필요한 기능 제공
public class test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
int sum = 0;
for (int i = 1; i <= 10; i++)
{
// Debug.Log("i의 값 : ",i);
sum += i;
}
Debug.Log(sum);
}
}
결과값 보기
더보기
// 1부터 10보다 값이 작아질 때 까지 i의 값을 sum 변수에다 더한다.
// 주석을 해제하면 i의 값도 Console에 찍힌다. i의 값을 확인하는 방법은 위와 같다.
55
반응형
'개발 > 유니티(UNITY)' 카테고리의 다른 글
2.7 메서드 만들기 (0) | 2023.09.08 |
---|---|
2.6 배열 사용하기 (0) | 2023.09.08 |
2.5 제어문 사용하기 (0) | 2023.09.07 |
2.4.2 변수와 연산 (0) | 2023.09.07 |
2.3 스크립트 첫 걸음 (0) | 2023.09.06 |