Unity C#スクリプトショートTips

Unityでゲームを開発する際に役立つC#スクリプトの簡潔なTipsを紹介します。

2つのGameObject間の距離を計算する

C#
// gameObjectAとgameObjectBの距離を計算
float distance2D = Vector2.Distance(gameObjectA.transform.position, gameObjectB.transform.position);

GameObjectにアタッチされているスクリプトを参照する

C#
// GameObjectにMyScriptがアタッチされている場合
MyScript myScript = gameObject.GetComponent<MyScript>();

GameObjectにスクリプトをアタッチする

C#
// GameObjectにMonoBehaviourを継承しているMyScriptクラスをアタッチ
public class GameObjectScript : MonoBehaviour
{
    private MyScript myScript;
    
    public void AttachMyScript()
    {
        myScript = gameObject.AddComponent<MyScript>();
    }
}

Animatorにアニメーション名を指定して再生させる

C#
// GameObjectにMyScriptがアタッチされている場合
Animator animator = gameObject.GetComponent<Animator>();
// アニメーション名がPlayrRunningのアニメーションを再生
animator.Play("PlayrRunning");

AnimatorにAnimationを再生させる

C#
public void PlayAnimation(Animation animation)
{
    // GameObjectにMyScriptがアタッチされている場合
    Animator animator = gameObject.GetComponent<Animator>();
    // Animationをstringに変換してPlay()の引数に
    animator.Play(animation.ToString());
}

Animatorが再生中のAnimationの名前を取得

C#
public string GetCurrentAnimationName()
{
    // GameObjectにMyScriptがアタッチされている場合
    Animator animator = gameObject.GetComponent<Animator>();
    AnimatorClipInfo[] clipInfo = animator.GetCurrentAnimatorClipInfo(0);
    if (clipInfo != null && clipInfo.Length > 0)
    {
        return clipInfo[0].clip.name;
    }
    return "";
}

インスペクターからメソッドを実行できるようにする

C#
public class GameObjectScript : MonoBehaviour
{
    public void ClassMeshod()
    {
      // 実行対象の処理
    }

    [ContextMenu("Test From Inspector")]
    private void TestClassMethod() { 
      // インスペクターから実行
      ClassMeshod();
    }
}

TextMeshProのテキストを変更

C#
public class ExampleClass : MonoBehaviour
{
    public TextMeshProUGUI targetText;
    
    public void UpdateText(string newText)
    {
        targetText.text = newText;
    }
}

TextMeshProの文字色を変更

C#
public class ExampleClass : MonoBehaviour
{
    public TextMeshProUGUI targetText;
    
    public void UpdateTextColor()
    {
        targetText.color = Color.white;
    }
}

投稿日

カテゴリー:

投稿者:

タグ: