Unity開発で躓いたので自分用にメモ。
やりたいことは「ボタンを押したらテキストをAからBに切り替える(スクリプトで)」。
ButtonからGetComponentでTextが取得できない。
UIのButtonには子オブジェクトとしてTextが含まれているので、
普通にGetComponentで取得できるんだろうと思っていたんですが、以下のようなエラーが。。
NullReferenceException: Object reference not set to an instance of an object
つまり、TextはButtonに含まれていない、ただの親子関係。(今思えば当たり前だけど)
ButtonのTextはGetComponentInChildrenで取得できる!
最終的に以下の方法でできました。
ButtonのTextは子オブジェクトなので、「GetComponentInChildren」で取得できます。
*ちなみに似たようなメソッドで「GetComponentsInChildren」っていうのがありますが、これだとエラーが出るので注意。
public GameObject ChangeButton; public bool isModeA = false; //ボタンのテキストを切り替える public void ChangeText(){ if (isModeA) { //表示をAからBにする isModeA = false; ChangeButton.GetComponentInChildren<Text> ().text = "B"; } else { //表示をBからAにする isModeA = true; ChangeButton.GetComponentInChildren<Text> ().text = "A"; } }
上記の例だと、isModeAの判定で、ChangeButtonのテキストをAかBに切り替えてます。
やり方忘れたらこの記事見直すことにします。