<if文を使った場合>
(スクリプト)
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ColorChange : MonoBehaviour { private MeshRenderer mr; private int num = 0; private int colorNum = 3; void Start() { mr = GetComponent(); } void Update() { if(Input.GetKeyDown(KeyCode.Space)) { num += 1; if(num % colorNum == 0) { mr.material.color = Color.red; } else if(num % colorNum == 1) { mr.material.color = Color.green; } else if (num % colorNum == 2) { mr.material.color = Color.black; } } } }
(実行結果)
- スペースキーを押すたびにオブジェクトの色が変化すれば成功
<switch文を使った場合>
(スクリプト)
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ColorChange2 : MonoBehaviour { private MeshRenderer mr; private int num = 0; private int currentNum; void Start() { mr = GetComponent<MeshRenderer>(); } void Update() { if(Input.GetKeyDown(KeyCode.Space)) { num += 1; currentNum = num % 3; switch(currentNum) { case 0: mr.material.color = Color.blue; break; case 1: mr.material.color = Color.yellow; break; case 2: mr.material.color = Color.gray; break; } } } }
(実行結果)
- スペースキーを押すたびにオブジェクトの色が変化すれば成功