[Unity] 並行処理とclass
簡単なゲームであればMainCameraにアタッチしたスクリプト一個ですべてのオブジェクトの挙動を管理できるかもしれませんが、この方法で困るのが例えば あるオブジェクトが時間変化している間に他の動作もしたい時。
そして、これをカードにアタッチします。それをMainCameraのスクリプトから呼び出すには、
とすればOK。これでbig.cs中の関数Switch ()が呼び出されます。
また、得点を随時表示させたい時も同じように、変数iscoreだけメインのスクリプトで管理しておいて、それを文字オブジェクトにアタッチしてスクリプトが読み込み、表示させることができます。
======================================
選択したカードを一定時間大きく見せたい場合を例としてあげると、大きく見せている間に他のカードの選択を受け付けるなどの並行動作を処理するのが難しい。というかコードがやたら複雑になっていく。
そこで、今までどう使えば良いか分からず敬遠していたクラス分けが有用になってきます。
例えば、一定時間だけ自動的にカードを大きくし、かつ前面に出しておきたい時、「big.cs」というスクリプトを作り、「big」というクラスを作ります。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class big : MonoBehaviour {
public float life_time = 1.0f, xx=0.0f,yy=0.0f,zz=0.0f;
float time = 0f;
public bool a = false;
public void Switch (){
time = 0;
a = true;
Vector3 sc = gameObject.transform.localScale;
xx = sc.x;
yy = sc.y;
sc.x *= 2.0f; //2倍の大きさにする
sc.y *= 2.0f;
gameObject.transform.localScale = sc;
Vector3 pos = gameObject.transform.position;
zz = pos.z;
pos.z -= 5.0f; //zを-5(前に出す)
gameObject.transform.position = pos;
}
void Update () {
time += Time.deltaTime;
if (a && time > life_time) {
Vector3 sc = gameObject.transform.localScale;
sc.x = xx;
sc.y = yy;
gameObject.transform.localScale = sc;
Vector3 pos = gameObject.transform.position;
pos.z = zz;
gameObject.transform.position = pos;
a = false;
}
}
}
big [適当な名前] = [big.csをアタッチしたオブジェクト].GetComponent (); [適当な名前].Switch ();
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class score : MonoBehaviour {
void Update () {
Text txt = this.GetComponent();
txt.text = "Count : "+[メインのスクリプト].iscore;
}
}
まとめると、一般的に他のスクリプトの関数や変数を参照したい時は、
別のスクリプトにある関数の呼び出し:
別のスクリプトにある変数の指定:
別のスクリプトにある関数の呼び出し:
[別のスクリプト名(=クラス名)] [適当な名前] = [別のスクリプトをアタッチしたオブジェクト] .GetComponent<[別のスクリプト名]> ();
[適当な名前].[呼び出したい関数] ();
別のスクリプトにある変数の指定:
[別のスクリプト名(=クラス名)].[読み書きしたい変数]
(ただし参照する関数や変数はpublicにしておくこと)
追記:staticにもしないと多分エラー出る
追記:staticにもしないと多分エラー出る
======================================

コメント
コメントを投稿