まゆたまガジェット開発逆引き辞典

電子工作やプログラミングのHowtoを逆引き形式で掲載しています。作りたいモノを決めて学んでいくスタイル。プログラマではないので、コードの汚さはお許しを。参照していないものに関しては、コピペ改変まったく問いません

同じプロジェクト間、違うスクリプトでのデータの受け渡し

同じプロジェクトの別のスクリプトで変数とそのデータを使いまわしたいことがあります。
そのときのデータを受け渡し(正確には読み取り)のメモです。

準備

1.「GameObject」メニュー→「Create Empty」で空のオブジェクトを2つ作る
2.それぞれの名前を「Send」「Recieve」などにする。同じ名前にしないよう気をつける
3.「Assets」を右クリックしてスクリプトを2つ作り、「SendScript」「RecieveScript」などと名前をつける
4.「Send」オブジェクトには「SendScript」を、「Recieve」オブジェクトには「RecieveScript」をドラッグ&ドロップする
5.「SendScript」と「RecieveScript」をダブルクリックしてスクリプトを書く

スクリプト 「SendScript」データを送る方(参照先)

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

public class SendScript : MonoBehaviour {

//この値を「RecieveScript」に送る(参照する)
public int ScoreData = 100;

	void Start () {
		
		

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

スクリプト 「RecieveScript」データを受け取る方(処理する先)

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

public class recieveScript : MonoBehaviour {

//この2つの変数が必要
 GameObject scoreBox;
SendScript script; 


	// Use this for initialization
	void Start () {
	
//Sendというオブジェクトを探す
		scoreBox = GameObject.Find ("Send");
        script = scoreBox.GetComponent<SendScript>();

//新しく変数を作って、「SendScript」の変数「ScoreData」を入れる
		int score = script.ScoreData;

        Debug.Log ("スコアは" + score);


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


    
}