はじめに
この記事はUnityで,
- スクリプトから他のスクリプトの変数やメソッドを呼び出したい人,
- スクリプトをGameObjectにアタッチしなくても, そのスクリプトの変数やメソッドを呼び出したい人
向けに書きました.
ただし呼び出される側のスクリプトは, StartやUpdateのようなイベント関数を含まず, 変数や自作のメソッドだけを含むことにします.
簡単なことですが, ググってもあまり情報がなかったので残しておきます.
呼び出される側のスクリプト
Another.cs
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;// 呼び出される側のスクリプト. GameObjectにアタッチしない.// StartやUpdateを使わないため, MonoBehaviourは不要.// 他のスクリプトから読み込むため, publicを付ける.publicclassCallee{// 呼び出される変数publicintexampleNumber=17;// 呼び出されるメソッドpublicvoidSup(){Debug.Log("Good!");}}
もちろん, Another.csはどのGameObjectにもアタッチしません
呼び出す側のスクリプト
UsingOtherComponents.cs
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;// 呼び出す側のスクリプト. GameObjectにアタッチする.publicclassUsingOtherComponents:MonoBehaviour{voidStart(){// Another.csのCalleeのインスタンス化Callee_Callee=newCallee();// 変数の呼び出し.int_exampleNumber=_Callee.exampleNumber;Debug.Log("Eample number is "+_exampleNumber);// メソッドの呼び出し._Callee.Sup();}}
4.UsingOtherComponents.csをGameObjectにアタッチします.