Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8895

【Unity】スクリプトをGameObjectにアタッチしなくても呼び出せるよっ

$
0
0

はじめに

この記事はUnityで,

  • スクリプトから他のスクリプトの変数やメソッドを呼び出したい人,
  • スクリプトをGameObjectにアタッチしなくても, そのスクリプトの変数やメソッドを呼び出したい人

向けに書きました.
ただし呼び出される側のスクリプトは, StartやUpdateのようなイベント関数を含まず, 変数や自作のメソッドだけを含むことにします.
簡単なことですが, ググってもあまり情報がなかったので残しておきます:wink:.

呼び出される側のスクリプト

  1. Assetsの中にAnother.csというスクリプト(呼び出される側)を用意します:point_down:スクリーンショット 2019-10-31 15.34.05.png
  2. Another.cs:point_down:を書き込みます.
Another.cs
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;// 呼び出される側のスクリプト. GameObjectにアタッチしない.// StartやUpdateを使わないため, MonoBehaviourは不要.// 他のスクリプトから読み込むため, publicを付ける.publicclassCallee{// 呼び出される変数publicintexampleNumber=17;// 呼び出されるメソッドpublicvoidSup(){Debug.Log("Good!");}}

もちろん, Another.csはどのGameObjectにもアタッチしません:thumbsup:

呼び出す側のスクリプト

  1. Assetsの中にUsingOtherComponents.csというスクリプトを用意します. スクリーンショット 2019-10-31 15.34.29.png
  2. UsingOtherComponents.cs:point_down:を書き込みます.
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();}}

3.:point_down:のようにGameObjectを用意します.
スクリーンショット 2019-10-31 15.52.32.png

4.UsingOtherComponents.csGameObjectにアタッチします:point_down:.
スクリーンショット 2019-10-31 15.54.15.png

実行結果

それでは実行してみましょっ!
スクリーンショット 2019-11-07 16.33.29.png
ちゃんと呼び出せてます:wink:.


Viewing all articles
Browse latest Browse all 8895

Trending Articles