LoginSignup
146
118

More than 5 years have passed since last update.

[Unity]他のオブジェクトについているスクリプトの変数を参照したり関数を実行したりする。

Last updated at Posted at 2017-04-15
Unityちゃんの中にあるUnityChanScript内に定義されている変数「int HP」と関数「Attack()」を、別オブジェクトGameManager内から利用する。

Unityちゃんの状態

スクリーンショット 2017-04-16 0.09.40.png

UnityChan.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UnityChanScript : MonoBehaviour {

    public int HP = 100;

    // Use this for initialization
    void Start () {

    }

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

    }

    public void Attack() {
        Debug.Log ("UnityChan_Attack!");
    }
}

このとき変数、関数ともに状態を「public」にしておかないと別のクラスから参照できない。

参照する側のスクリプトの作成

スクリーンショット 2017-04-16 0.20.00.png

GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManagerScript : MonoBehaviour {

    GameObject unitychan; //Unityちゃんそのものが入る変数

    UnityChanScript script; //UnityChanScriptが入る変数

    // Use this for initialization
    void Start () {
        unitychan = GameObject.Find ("unitychan"); //Unityちゃんをオブジェクトの名前から取得して変数に格納する
        script = unitychan.GetComponent<UnityChanScript>(); //unitychanの中にあるUnityChanScriptを取得して変数に格納する
    }

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

        int unitychanHP = script.HP; //新しく変数を宣言してその中にUnityChanScriptの変数HPを代入する
        Debug.Log ("UnityちゃんのHPは" + unitychanHP);

        script.Attack (); //UnityChanScriptにある関数Attackを実行する

    }
}

実行結果

スクリーンショット 2017-04-16 0.35.44.png

まとめ

  • 参照したいオブジェクトを「GameObject」型の変数で取得する
  • 参照したいスクリプトを「スクリプト名」型の変数で取得する
  • 「スクリプトを入れた変数名」.「参照したい変数」のように間にドットを入れて参照する
146
118
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
146
118