概要
Unityのスクリプトでよく使う関数などをまとめておく(随時追加予定)
C#関数
✨連想配列
Dictionary(Key, Value)の形で値を保持する。以下は宣言と初期化。
// 初期化①
Dictionary<string, int> fruits = new Dictionary<string, int>()
{
["apple"] = 100,
["mikan"] = 120
};
// 初期化②
Dictionary<string, int> Player = new Dictionary<string, int>()
{
{ "player", 100 },
{ "enemy", 200 }
};
✨切り上げ・切り捨て・四捨五入
切り上げ(正の無限大に向かう)
float num1 = 1.15f;
float num2 = -1.25f;
Debug.Log(Mathf.Ceil(num1)); // 2
Debug.Log(Mathf.Ceil(num2)); // -1
切り捨て
using System; // Math使用時は必要
float num1 = 1.15f;
float num2 = -1.25f;
// ①負の無限大に向かう
Debug.Log(Mathf.Floor(num1)); // 1
Debug.Log(Mathf.Floor(num2)); // -2
// ②0に向かう
Debug.Log(Math.Truncate(num1)); // 1
Debug.Log(Math.Truncate(num2)); // -1
四捨五入
using System; // Math使用時は必要
float num1 = 1.5f;
float num2 = 2.5f;
float num3 = -1.5f;
float num4 = -2.5f;
float num5 = 1.25f;
// ①偶数への丸め込み(切り上げの場合は一番近い偶数になる)
Debug.Log(Mathf.Round(num1)); // 2
Debug.Log(Mathf.Round(num2)); // 2
Debug.Log(Mathf.Round(num3)); // -2
Debug.Log(Mathf.Round(num4)); // -2
Debug.Log(Mathf.Round(num5)); // 1
// ②通常の四捨五入
Debug.Log(Math.Round(num1, MidpointRounding.AwayFromZero)); // 2
Debug.Log(Math.Round(num2, MidpointRounding.AwayFromZero)); // 3
Debug.Log(Math.Round(num3, MidpointRounding.AwayFromZero)); // -2
Debug.Log(Math.Round(num4, MidpointRounding.AwayFromZero)); // -3
Debug.Log(Math.Round(num5, MidpointRounding.AwayFromZero)); // 1
// ③桁数指定 (第2引数に得たい小数の桁数を指定)
Debug.Log(Math.Round(num5, 1, MidpointRounding.AwayFromZero)); // 1.3
✨配列内をランダムに取得する
string[] words = new string[3] {"a","b","c"};
Debug.Log(words[Random.Range(0, words.Length)]);
// b(出力はランダムに変化)
✨文字列をint型へ変換する
using System;
int num = Int32.Parse("123");
int n = int.Parse("456");
✨enum(列挙型)
「列挙型」は複数の変数に一連の整数値をつける場合に便利。
変数に入るパターンが決まっている場合に有用。
// 定数値はデフォルトでintの0から割り振られる
enum Type
{
Easy, // 定数値0
Normal, // 定数値1
Hard // 定数値2
}
// 定数値の指定も可能
enum Week
{
Mon = 1,
Wed = 3,
Fri = 5
}
void Main()
{
Debug.Log(Type.Easy); // Easy
Debug.Log((int)Type.Hard); // 2
Debug.Log((int)Week.Fri); // 5
}
✨フォルダ内のファイルを取得する
using System.IO;
// GetFiles引数(フォルダのパス, ファイル名)
string[] files = Directory.GetFiles(Application.dataPath + "/Resources/Prefabs", "*.prefab");
✨テキストの色指定
[SerializeField] private Text helloText;
void ChangeTextColor()
{
helloText.text = "Hello!!";
helloText.color = Color.red; // 定数指定(他:black, gray, magenta, clear)
helloText.color = new Color(1.0f, 1.0f, 0.0f, 0.5f) // 色指定(R, G, B, 透明度)
// 16進数指定
ColorUtility.TryParseHtmlString("#3399cc", out Color newColor); // 引数(16進色, 出力変数)
helloText.color = newColor;
}
コルーチン
一旦処理を止めたい場合などに使用
✨基本的なコルーチン処理
void Start()
{
StartCoroutine(TextOutPut());
}
IEnumerator TextOutPut()
{
yield new WaitForSeconds(1.0f);
Debug.Log("Hello!!"); // 1秒後に出力される
}
✨コルーチンの中からコルーチンを呼び出す
private
void Start()
{
StartCoroutine(TextOutPut());
}
IEnumerator TextOutPut()
{
yield return OutputHello(); // OutputHelloが終わるまで待機
Debug.Log("World!!");
}
IEnumerator OutputHello()
{
yield return new WaitForFixedUpdate(3.0f);
Debug.Log("Hello!");
}
/* 出力 */
// Hello!
// World!!
✨コルーチンの中断・終了
// 1フレーム中断する
yield return null;
// 終了する(再開しない)
yield break;
ゲームオブジェクトの設定
✨オブジェクトを生成する
// 引数(ゲームオブジェクト, 位置, 回転)
Instantiate(gameObj, Vector3.zero, Quaternion.identity);
✨親オブジェクトを設定(子オブジェクトとして生成する)
以下の例ではinspectorウインドウで親オブジェクトをあらかじめ設定
[SerializeField] private GameObject parentObj; // 親オブジェクト
// 子オブジェクトを生成して親オブジェクトの設定する
GameObject childObj = Instantiate(obj, Vector3.zero, Quaternion.identity);
childObj.transform.parent = parentObj.transform;
✨オブジェクト名に[Clone]がつかないようにする
ゲームオブジェクト生成時、オブジェクト名に[Clone]がつく。これをつかないようにする。
GameObject obj = Instantiate(gameObj, Vector3.zero, Quaternion.identity);
obj.name = gameObj.name;
✨プロパティをInspector上からオブジェクトを設定できるようにする
[SerializeField] private GameObject player;
// または
public Text text;
[SerializeField]とした場合、Unityエディタで[CS0649警告]が表示される。
これが邪魔な場合はデフォルトを設定するのが一案としてある。
[SerializeField] private GameObject player = default;
✨Prefabをゲームオブジェクトに設定する
あらかじめ、Assetsフォルダ内に「Resources」フォルダを作成し、その中にPrefabをおく。
(以下の例ではResourcesフォルダ内にPrefabsフォルダを作り、その中にobj1というprefabを置いている。)
GameObject obj = new GameObject();
obj = (GameObject)Resources.Load("Prefabs/obj1")
✨ゲームオブジェクトの検索(Find)
// Hierarchyウインドウの中から、指定した文字列に一致したゲームオブジェクトを1つ取得
GameObject gMaster = GameObject.Find("GameMaster");
✨2D画像の設定(Sprite)
以下の例ではinspectorウインドウでSprite画像を設定し、ゲームオブジェクトに設定
[SerializeField] private Sprite sprite_image;
gameObj.GetComponent<SpriteRenderer>().sprite = sprite_image;
UIの設定
✨クリックイベントに引数を設定する
// 単純に引数を記述する、あとはInspectorウインドウで設定する
public void onClickButton(GameObject obj)
{
// 処理を記述
}
✨テキストの表示・非表示
[SerializeField] private Text helloText;
void ShowText()
{
if (helloText.enabled)
{
helloText.enabled = false; // 非表示にする
}
else
{
helloText.enabled = true; // 表示する
}
}