LoginSignup
1
2

More than 5 years have passed since last update.

[Unityで学ぶC#] 2 条件分岐

Last updated at Posted at 2017-03-03
1 / 11

If文とは

ある条件を満たした時だけXXをしたいという時に使います.


  • HPがなくなったとき
  • 矢印キーを押した時
  • フラグを回収した時

サンプル

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class IfExample : MonoBehaviour {

    void Start () {
        // 数値の比較
        int hp = 10;

        if (hp > 8) { 
            Debug.Log ("HPは8より高い!");
        }
    }
}

実行結果

実行するとこのような結果が出ると思います.

スクリーンショット 2017-02-26 12.21.21.png


ポイント

この部分で条件を設定しています.

if(hp > 8)  // hpが8よりも大きかったら

ifと書いてあるところの()の中身が正しければ
{}の中が実行されます.


つまりこういうことです.

if(条件){
  実行される処理
}

サンプル2

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class IfExample : MonoBehaviour {

    void Start () {
        // 数値の比較
        int hp = 5;

        if (hp < 8) { 
            Debug.Log ("HPは8より低い!");
        }
    }
}

ポイント

このように条件にはいくつかの種類があります.

一つ目の例

if(hp > 8)  // 8より大きい

二つ目の例

if(hp < 5)  // 5より小さい

よく使う条件

条件 意味
a == b aとbは等しい
a != b aとbは等しくない
a > b aはbより大きい
a >= b aはb以上
a < b aはbより小さい
a <= b aはb以下

おわり

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2