Game Development, 게임개발/개발

C#에서의 삼항 연산자 Ternary Operator [Unity]

게임이 더 좋아 2021. 3. 22. 05:18
반응형
728x170

많이 쓰려면 많이 쓸 수 있지만

몰라서 못쓰는 경우가 더 많은 것 같아서

알아보았다.

 


if, else문을 하나로 합쳐서 쓰는 것과 비슷하다.

 

"Boolean expression" + ? + "True, value" : "False, value" 

 

만약 이렇게 쓰지 않는다면

if (Boolean condition){

"참일 때 값"

}

else{

"거짓일 때 값"

}

이렇게 되었을 것이다.

 

직관적으로 이해하기 쉽게 도와주는 연산자이다.

 

using UnityEngine;
using System.Collections;

public class TernaryOperator : MonoBehaviour 
{
    void Start () 
    {
        int health = 10;
        string message;

        //This is an example Ternary Operation that chooses a message based
        //on the variable "health".
        message = health > 0 ? "Player is Alive" : "Player is Dead";
    }
}
반응형
그리드형