LoginSignup
6
5

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-11-07

はじめに

この記事は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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// 呼び出される側のスクリプト. GameObjectにアタッチしない.
// StartやUpdateを使わないため, MonoBehaviourは不要.
// 他のスクリプトから読み込むため, publicを付ける.
public class Callee
{
    // 呼び出される変数
    public int exampleNumber = 17;

    // 呼び出されるメソッド
    public void Sup()
    {
        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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// 呼び出す側のスクリプト. GameObjectにアタッチする.
public class UsingOtherComponents : MonoBehaviour
{
    void Start()
    {
        // Another.csのCalleeのインスタンス化
        Callee _Callee = new Callee();

        // 変数の呼び出し.
        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:.

6
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5