Unityでスクリプトを作成していてどこかで必要になってくるものの1つに他のスクリプト内で持っている変数にアクセスしたいということがあります。
はじめは少し悩まされましたが、備忘録として書き残しておきたいと思います。
1.他のクラス(スクリプト)内に持っている変数にアクセスする方法例
まずはじめに、アクセスを受ける側のスクリプトとしては、以下のように「timer」変数のあるAbcControllerScript クラスを持つものとして「AbcControllerScript.cs」という名前をつけて作成しておきます。
そして、これを「AbcController」という名前をつけたGameObjectにアタッチしておくこととします。
また、アクセスを受けるタイマー変数「timer」はpublicで宣言しておきます。
AbcControllerScript.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AbcControllerScript : MonoBehaviour { public float timer;//ゲーム制限時間タイマー // Start is called before the first frame update void Start() { timer = 30.0f; } }
これに対して、アクセスする側のスクリプトは、以下のようになります。
先程のスクリプト「AbcController.cs」をアタッチしたオブジェクト「AbcController」をFind()で洗い出し、さらに、洗い出したオブジェクトのスクリプトを変数に代入しています。
最後にそのスクリプトを代入した変数のtimer変数をDebug.Log()で表示することでtimer変数の値を表示することができるというものです。
DefControllerScript.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DefControllerScript : MonoBehaviour { private GameObject abcControllerObject;
AbcControllerScript abcControllerScript; // Start is called before the first frame update void Start() { // //残り時間タイマー用
abcControllerObject = GameObject.Find("AbcController");
abcControllerScript = abcControllerObject.GetComponent<AbcControllerScript>(); Debug.Log(abcControllerScript.timer); } }
以上が他のスクリプト内で持っている変数にアクセスする方法になります。
リンク