[過去ログ] 【ゲームエンジン】Unity初心者質問スレBuild4 (1002レス)
上下前次1-新
抽出解除 必死チェッカー(本家) (べ) 自ID レス栞 あぼーん
このスレッドは過去ログ倉庫に格納されています。
次スレ検索 歴削→次スレ 栞削→次スレ 過去ログメニュー
423(2): 423 2020/05/12(火)15:39 ID:oz8b1+GC(1/5) AAS
他のオブジェにアタッチしたスクリプトの変数をボタンを押して変更したいです。
Boolean(空オブジェ)にアタッチしているBoolean.cs の中の変数 bool BOOL を ボタンを押して、false から true にしたいです。
ヒエラルキーにあるオブジェ
Canvas
Button
Boolean(空のオブジェにBoolean.csアタッチ)
424(1): 423 2020/05/12(火)15:39 ID:oz8b1+GC(2/5) AAS
//■■■Booleanに付けたスクリプト■■
using UnityEngine;
public class Boolean : MonoBehaviour
{
public bool BOOL = false;
void Update()
{Debug.Log(BOOL);}
}
//■■■Buttonのクリックイベント■■
using UnityEngine;
public class Button : MonoBehaviour
{
bool BOOL;
public void Click()//ボタンのクリックイベント
{
BOOL = GameObject.Find("Boolean").GetComponent<Boolean>().BOOL;
if (BOOL == false)
{BOOL = true;}
else
{BOOL = false;}
}
}
ボタンを押してもDebug.Log(BOOL) が true にならないです。
Booleanの中のboolean型の変数 を true にしたいのでどうか教えてください。
427: 2020/05/12(火)16:22 ID:oz8b1+GC(3/5) AAS
>>425
ご親切な回答を有難うございます!
おかげ様で出来ました!
429(2): 2020/05/12(火)18:57 ID:oz8b1+GC(4/5) AAS
void OnEnable()
{
GameObject _button1 = GameObject.Find("Canvas").transform.Find("button1").gameObject;
_button1.gameObject.SetActive(true);
GameObject _button2 = GameObject.Find("Canvas").transform.Find("button2").gameObject;
_button2.gameObject.SetActive(false);
}
↑このようなコードをスタート関数を用いる方法で書き直しました↓
GameObject _button1;
GameObject _button2;
void Start()
{
_button1 = GameObject.Find("Canvas").transform.Find("button1").gameObject;
_button2 = GameObject.Find("Canvas").transform.Find("button2").gameObject;
}
void OnEnable()
{
_button1.gameObject.SetActive(true);
_button2.gameObject.SetActive(false);
}
そうしたら_button1.gameObject.SetActive(true);の行の所で
NullReferenceException: Object reference not set to an instance of an object というエラーがでました。
どのオブジェクトにも参照を持たない参照変数にアクセスしようとするエラーらしいのですが、一応動作はしている見たいで、参照もできている感じですが無視していいのでしょうか。
スタート関数を用いないほうがいいのでしょうか。
434: 429 2020/05/12(火)20:19 ID:oz8b1+GC(5/5) AAS
>>430
どうも有難うございます。Debug.Logで調べてみたのですが
どうやらスタート関数よりOnEnable()関数の方が先に呼ばれているようです。
それでうまくいってなかったのだと思います。
OnEnable()の中では、
_button1.SetActive(true);
として、gameObjectはいらないと思います。
↑了解いたしました。有難うございます。
上下前次1-新書関写板覧索設栞歴
スレ情報 赤レス抽出 画像レス抽出 歴の未読スレ
ぬこの手 ぬこTOP 0.026s