閲覧ありがとうございます。
C#を勉強しているものです。
現在GameController.csにある変数を、他クラスItem.csにて書き換えたいと思っています。
(挙動としては、Itemクラスでの値の変更をトリガーにしてGamecontrollerクラスのメソッドを動かしたいと考えております。unityのUpdate関数などを使わず実装したいです。)
他の質問者様の回答やネットで調べてみて色々試して以下の方法で試してみましたがうまくいきません。
C#に詳しい方いらっしゃいましたらご教授いただけないでしょうか。何卒よろしくお願いいたします。
1.GameController.csをItemでインスタンス化して値を代入する。→コンパイルエラーにはならないがnullになる。
2.GameController.csでバプリック変数を定義してItem.csから参照する。→コンパイルエラー。 error CS0120: An object reference is required to access non-static memberのエラーが出る。
C#
1using System; 2using System.Collections; 3using System.Collections.Generic; 4using UnityEngine; 5using UnityEngine.UI; 6 7public class GameController : MonoBehaviour { 8 9 public Text scoreLabel; 10 public GameObject winnerLabelObject; 11 12 public GameController instance = null; 13 14 private bool ObjDestroyed; 15 public bool _ObjDestroyed 16 { 17 get { 18 return ObjDestroyed; 19 } 20 21 set{ 22 ObjDestroyed = value; 23 } 24 25 } 26 27 private void Awake() 28 { 29 instance = this; 30 ObjDestroyed = false; 31 } 32 33 34 public void SetText() 35 { 36 if (ObjDestroyed != false) 37 { 38 int count = GameObject.FindGameObjectsWithTag ("Item").Length; 39 scoreLabel.text = count.ToString (); 40 41 if (count == 0) { 42 //オブジェクトをアクティブにする 43 winnerLabelObject.SetActive (true); 44 } 45 } 46 } 47} 48
C#
1using System; 2using System.Collections; 3using System.Collections.Generic; 4using UnityEngine; 5 6public class Item : MonoBehaviour { 7 8 private bool getObj; 9 10 private GameController _GameController = new GameController(); 11 12 13 //トリガーとの接触時に呼ばれるコールバック。 14 public void OnTriggerEnter(Collider hit) 15 { 16 //接触対象はPlayerタグですか? 17 if (hit.CompareTag ("Player")) 18 { 19 //このコンポーネントを持つGameObejctを破棄する。 20 Destroy (gameObject); 21 22 //1 23 _GameController._ObjDestroyed = true; 24 25 //2 26 GameController.instance._ObjDestroyed = true; 27 } 28 } 29} 30
主にこちらの記事を参考にしました。↓
別のクラスの変数の値を変更したい
回答3件
あなたの回答
tips
プレビュー