概要
UdonSharpはC#の文法を用いてプログラミングを行いますが、そのコードはUdon VMという特殊な環境で動作するため、標準的なC#の全ての機能が利用できるわけではありません。開発を効率的に進めるためには、何が利用でき、何が利用できないのかを正確に把握しておくことが不可欠です。
本記事では、UdonSharp開発において使用可能なC#の主要機能と、Udon VMの制約によって課される主な制限事項について具体的に解説します。
利用可能なC#の主要機能
UdonSharpでは、C#の基本的な機能の多くがサポートされています。これらを組み合わせることで、ほとんどのギミックを実装することが可能です。
1. 変数とデータ型
- 基本データ型:
int,float,double,bool,string,charなどの基本的な値型はすべて利用できます。 - Unityの型:
Vector3,Quaternion,Color,GameObjectなど、Unityエンジンが提供するほとんどのクラスや構造体を利用できます。 - 配列:
int[],GameObject[]のような一次元配列は問題なく使用できます。多次元配列(例:int[,])もサポートされています。
public class VariableExample : UdonSharpBehaviour
{
// 基本データ型
public int score = 0;
public string playerName = "Default Player";
public bool isGameActive = false;
// Unityの型
public Vector3 initialPosition = new Vector3(0, 1, 0);
public GameObject targetObject;
// 配列
public Transform[] waypoints;
}
2. 制御構文
プログラムの流れを制御するための構文は、標準的なC#と同様に使用できます。
- 条件分岐:
if,else if,else,switch - 繰り返し:
for,foreach,while,do-while - ジャンプ:
break,continue,return
void CheckScore()
{
if (score >= 100)
{
Debug.Log("勝利!");
}
else
{
Debug.Log("まだ足りません");
}
}
void ProcessWaypoints()
{
foreach (Transform waypoint in waypoints)
{
Debug.Log(waypoint.name);
}
}
3. メソッド(関数)
処理をまとめるためのメソッドも定義・呼び出しが可能です。引数や戻り値もサポートされています。
// 戻り値と引数を持つメソッド
private int Add(int a, int b)
{
return a + b;
}
void CalculateSum()
{
int result = Add(5, 3); // resultは8になる
Debug.Log(result);
}
4. プロパティ
C#のプロパティ(getterとsetter)もサポートされています。
private int _health = 100;
public int Health
{
get { return _health; }
set { _health = Mathf.Clamp(value, 0, 100); }
}
5. その他のサポートされている機能
以下の機能もUdonSharpで利用可能です。
- out/refパラメータ: メソッドの引数で
outやrefキーワードが使用できます。 - 拡張メソッド: 既存の型に独自のメソッドを追加できます。
- null条件演算子:
?.や??演算子が使用できます。 - 文字列補間:
$"スコア: {score}"のような書き方ができます。
// out パラメータの例
public bool TryGetPlayerScore(string playerName, out int score)
{
// 処理...
score = 100;
return true;
}
// 呼び出し側
if (TryGetPlayerScore("Player1", out int result))
{
Debug.Log($"