他のクラスのメソッドを呼ぶには
Unity では、Boo、Javascript、C#という3つの言語をスクリプト言語として使うことができるようになっとるけど、それぞれ言語特性が違うけぇ、使い勝手が結構違うところがある。たとえば MonoBehavior のサブクラスで独自のメソッドを拡張した場合、
public class TestScript : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } // ここが拡張 public Texture GetTexture() { return guiTexture.texture; } }
Javascript のような言語であれば、ゲームオブジェクトからコンポーネントを取得して、そのままメソッドを呼ぶことができる。じゃけど C# の場合は、基底の Component クラスとして見えとるけぇ、 getTexture() はコールできん。 C# の場合は、キャストせにゃあいけん。
GameObject foo = GameObject.Find("player"); TestScript component = (TestScript)foo.GetComponent("TestScript"); guiTexture.texture = component.getTexture();
戻り値があるときは少々面倒じゃけど、メッセージ通信だけでやるという方法もある。ゲームエンジン上のスクリプティングとしてみりゃあ、相性は悪ぃこたぁない*1。
// The class of player_a public class FooA : MonoBehaviour { // public void CopyTexture(GameObject obj) { obj.sendMessage("SetTexture", guiTexture.texture); } } // The class of player_b public class FooB : MonoBehaviour { // public void SetTexture(Texture texture) { guiTexture.texture = texture; } void test() { GameObject.Find("player_a").SendMessage("CopyTexture", this); } }
メニュープログラムとか、GUI系テクスチャ制御とか、リソースマネージャとか、いわゆるシステム系のコードを書いとるときゃあやりにくいが、ゲームプレイコードのオブジェクト間の通信では、ダブルディスパッチになることは滅多にないけぇ、わりとしっくりくるやり方です。