本日は Unity の小ネタ枠です。
UnityEngine.Randomを使って様々なランダム値を取得する方法を記事にします。
UnityEngine.Random
UnityEngine.Random はランダム値を生成するクラスです。
数値のほか、Unity 固有の型である Vector3 型や Quaternion 型などのランダム値を生成することができます。
docs.unity3d.com
実行例
ランダム値を作成する各関数を実行してログに出力するスクリプトを作成しました。
・UnityRandomTest.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class UnityRandomTest : MonoBehaviour { // Start is called before the first frame update void Start() { // 0.0f ~ 1.0fの間のランダム数値を返します float randomValue = Random.value; Debug.Log("Random.value : " + randomValue.ToString()); // 半径 1 の円の内部のランダムな点を返します Vector2 insideUnitCircle = Random.insideUnitCircle; Debug.Log("Random.insideUnitCircle : " + insideUnitCircle.ToString()); // 半径 1 の球体の内部のランダムな点を返します Vector3 insideUnitSphere = Random.insideUnitSphere; Debug.Log("Random.insideUnitSphere : " + insideUnitSphere.ToString()); // 半径 1 の球体の表面上にランダムな点を返します Vector3 onUnitSphere = Random.onUnitSphere; Debug.Log("Random.onUnitSphere : " + onUnitSphere.ToString()); // ランダムな Quaternion 型の値を返します Quaternion rotation = Random.rotation; Debug.Log("Random.rotation : " + rotation.ToString()); // 一様分布のランダムな Quaternion 型の値を返します Quaternion rotationUniform = Random.rotationUniform; Debug.Log("Random.rotationUniform : " + rotationUniform.ToString()); // HSV で アルファ値を持つランダムな色を生成します Color colorHSV = Random.ColorHSV(); Debug.Log("Random.colorHSV : " + colorHSV.ToString()); // 0 ~ 9 の間のランダム数値(int) int randomRange_Int = Random.Range(0, 10); Debug.Log("Random.Range_Int : " + randomRange_Int.ToString()); // 0.0f ~ 10.0f の間のランダム数値(float) // float 指定の場合は出力に Max 値が含まれます float randomRange_Float = Random.Range(0.0f, 10.0f); Debug.Log("Random.Range_Float : " + randomRange_Float.ToString()); } }
オブジェクトに追加して実行結果を確認しました。
Vector や Quaternion のランダム値を取得したい場合に役立ちます。