LoginSignup
0
0

More than 3 years have passed since last update.

スクリプト内で別スクリプトの関数を実行する

Posted at

オブジェクトAからオブジェクトBの値を持ってくるとか、実行する的なことができる。
Hierarchyで

"Create Empty"してオブジェクト名をGameObjectからAdminに変える(名前は何でもよい)

次に2D Object → "sprite"でNew Spriteを追加し、Assetsに画像を追加して

New Spriteに対応付けする。

admin_init.png

AdminとNew Spriteにそれぞれ別のスクリプトをAdd Componentする。

admin_scriptadd.png

New Spreteのスクリプトを以下のようにアタッチ

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpriteScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }
    // Update is called once per frame
    void Update()
    {

    }
    // public付けないとダメ
    public void PrintSpriteName()
    {
        print(this.gameObject.name);
    }
}

Adminのスクリプトを以下のようにアタッチ

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AdminScript : MonoBehaviour
{
    // public付けないとダメ
    public GameObject sprite_object;
    // Start is called before the first frame update
    void Start()
    {
        //sprinte_object<>
    }
    // Update is called once per frame
    void Update()
    {
        //test[0].GetComponent<CurrentSelected>().aaa();
        sprite_object.GetComponent<SpriteScript>().PrintSpriteName();
    }
}

すると、AdminのInspectorのAdminScriptコンポーネントにスクリプト内で宣言した

Sprite_object

が追加されるので、の⦿マークを押してNew Spriteを入れる(もしくはドラッグ&ドロップ)。

admin_checkbox.png

これで実行すれば、Adminスクリプト内でNewSpriteスクリプト内の関数を呼び出せる。

admin_result.png

値渡したい場合はset、getのプロパティ関数作ってやればよい。

0
0
0

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
0
0