for문은 반복 횟수를 지정하면 자동으로 반복 횟수만큼 처리한다.
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 (변수 초기화; 반복 조건식; 변수 갱신)
{
처리
}
}
// Update is called once per frame
void Update()
{
}
}
for문의 괄호 안에는 변수 초기화, 반복 조건식, 변수 갱신이 입력되어야 한다.
변수 갱신에 입력한 식이 반복 조건식에 만족할 때까지 {처리}부분이 반복된다.
(변수 초기화는 아래 글을 참고)
https://greenchoco.tistory.com/104
유니티 C# 코딩 기본 구조
유니티에서 스크립트를 만들면 아래와 같이 기본 스크립트가 형성된다. 추가로 내가 void Start에 예제로 몇가지를 입력해보았다. using System.Collections; using System.Collections.Generic; using UnityEngine; public
greenchoco.tistory.com
예시
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 a = 0; a < 10; a++)
{
Debug.Log(a);
}
}
// Update is called once per frame
void Update()
{
}
}
결과값 : 0 1 2 3 4 5 6 7 8 9
몇가지 더 예시를 알아보면?
만약 아래처럼 입력하면 결과값은 0 2 4 6 8 이 출력된다.
for (int a = 0; a < 10; a+=2)
{
Debug.Log(a);
}
만약 아래처럼 입력하면 결과값은 5 4 3 2 1 이 출력된다.
for (int a = 5; a > 0; a--)
{
Debug.Log(a);
}
(참고로 ++, +=, --는 산술연산자로, 자세한 것은 아래 링크 참고)
https://greenchoco.tistory.com/111
C#기초 관계연산자 종류
연산자 관계연산자 뜻 == 비교연산자 왼쪽과 오른쪽이 같으면 참 != 비교연산자 왼쪽과 오른쪽이 다르면 참 > 비교연산자 왼쪽이 오른쪽 값보다 크면 참 = 비교연산자 왼쪽이 오른쪽 값보다 크거
greenchoco.tistory.com
그럼 1부터 10까지 모두 더하게 하려면?
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 a = 1; a <= 10; a++)
{
sum += a;
}
Debug.Log(sum);
}
// Update is called once per frame
void Update()
{
}
}
결과값 : 55
'유니티 C# > C#' 카테고리의 다른 글
C#기초 - 메서드(Method)란? (인수, 반환값, void 뜻) (0) | 2023.05.02 |
---|---|
C#기초 - 배열 사용법 (0) | 2023.05.02 |
C#기초 - if문 블록에서의 변수 범위 (0) | 2023.04.27 |
C#기초 - else if 조건식 사용방법 (0) | 2023.04.27 |
C#기초 - if문 조건식 사용방법 (0) | 2023.04.11 |
댓글