気軽に遊べるミニゲームを制作しています

ブラウザゲームまとめ

【unity】他クラスの変数を使う方法

Unity2D

1.使いたいクラスのついたオブジェクトをドロップして扱う(一番簡単)

テキストにintを移すコードAを準備します。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CodeA : MonoBehaviour
{
    public int codeAint=0;
    public Text txt;

    private void Update()
    {
        txt.text = codeAint.ToString();
    }
}

このコードAの変数を書き換えるコードBを作成します。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CodeB : MonoBehaviour
{
    public CodeA codeA;

    // Update is called once per frame
    void Update()
    {
        codeA.codeAint = 2;
    }
}

コードAをドロップします

コードAの変数が書き換えられます

2.GetComponentでクラスを取得する(ゲーム中に生成されたオブジェクトに使う)

ゲームではゲーム進行中に生成された敵のHP変数を減らしたいという時があると思います。

そんな時はGetComponentでクラスを取得する必要があります。
ゲーム開始後に作成されるゲームオブジェクト “codeAobject” を生成するGameManagerを作成します。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public GameObject codeAobject;

    // Start is called before the first frame update
    void Start()
    {
        Instantiate(codeAobject);
    }

}

コードAのついたオブジェクトを作成して、コードを修正します。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CodeA : MonoBehaviour
{
    public int codeAint=0;
    public Text txt;
    private GameObject gameTxt;

    private void Start()
    {
        gameTxt=GameObject.Find("Text (Legacy)");
        txt = gameTxt.GetComponent<Text>();
    }

    private void Update()
    {
        txt.text = codeAint.ToString();
    }

}

ゲーム開始後にTxtを変更したいオブジェクトをFindで取得します。

続いてコードBオブジェクトを作成して、コードBを修正します。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CodeB : MonoBehaviour
{
    public CodeA codeA;
    private GameObject codeAobject;

    // Update is called once per frame
    void Update()
    {
        codeAobject = GameObject.Find("CodeAobject(Clone)");
        codeA = codeAobject.GetComponent<CodeA>();
        codeA.codeAint = 2;
    }
}

生成されたCodeAobject(Clone)のCodeAを2へ書き換えることができました。

コメント

タイトルとURLをコピーしました