unityでの質問です。
画面上のボタンをクリックすることで、ボタンを用いて設置したテキストのActivateの変更と、テキストの変更をc#側のプログラムから実行することを目的としています。
GameManagerのインスペクター上でpublic変数とUIの紐づけは行っていますが、buttonMessageTextがnullで得られてしまいます。
cs
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5using UnityEngine.UI; 6 7public class GameManager : MonoBehaviour 8{ 9 public const int WALL_FRONT = 1; 10 public const int WALL_RIGHT = 2; 11 public const int WALL_BACK = 3; 12 public const int WALL_LEFT = 4; 13 public GameObject panelWalls; 14 private int wallNo; 15 16 public GameObject buttonMessage; //ボタン:メッセージ 17 public GameObject buttonMessageText;//メッセージテキスト 18 19 // Start is called before the first frame update 20 void Start() 21 { 22 wallNo = WALL_FRONT; 23 } 24 25 // Update is called once per frame 26 void Update() 27 { 28 29 } 30 31 public void PushButtonRight() 32 { 33 wallNo++; 34 if (wallNo > WALL_LEFT) 35 { 36 wallNo = WALL_FRONT; 37 } 38 DisplayWall(); 39 } 40 41 public void PushButtonLeft() 42 { 43 wallNo--; 44 if (wallNo < WALL_FRONT) 45 { 46 wallNo = WALL_LEFT; 47 } 48 DisplayWall(); 49 } 50 51//この部分でnullが返されているということが確認できました。 52 void DisplayMessage(string mes) 53 { 54 buttonMessage.SetActive (true); 55 //UnityEngine.Debug.Log("test"); 56 if(buttonMessageText.GetComponent<Text>()==null) 57 { 58 UnityEngine.Debug.Log("test"); 59 } 60 else 61 { 62 buttonMessageText.GetComponent<Text>().text = mes; 63 } 64 } 65 66 //向いている方向の壁を表示 67 void DisplayWall() 68 { 69 switch (wallNo) 70 { 71 case WALL_FRONT: //前 72 panelWalls.transform.localPosition = new Vector3(0.0f, 0.0f, 0.0f); 73 break; 74 case WALL_RIGHT: //右 75 panelWalls.transform.localPosition = new Vector3(-1000.0f, 0.0f, 0.0f); 76 break; 77 case WALL_BACK: //後 78 panelWalls.transform.localPosition = new Vector3(-2000.0f, 0.0f, 0.0f); 79 break; 80 case WALL_LEFT: //左 81 panelWalls.transform.localPosition = new Vector3(-3000.0f, 0.0f, 0.0f); 82 break; 83 } 84 } 85 86 public void PushButtonMemo() 87 { 88 //UnityEngine.Debug.Log("test"); 89 DisplayMessage("france"); 90 } 91 92 public void PushButtonMessage() 93 { 94 buttonMessage.SetActive(false); //メッセージを消す 95 } 96 97}
質問としては、buttonMessageTextをtextにアクセスできるようにするにはどうすればいいかということを教えていただきたいです。特にDisplayMessageで問題点が確認できています。
この内容は「UnityではじめるC#~知識ゼロからはじめるアプリ開発入門~」の内容ですが、同様のエラーが確認できませんでしたので、なにか間違っている点など教えていただきたいです。よろしくお願いいたします。
本当にbuttonMessageTextにTextをアタッチしておりますか?
buttonMessageTextの親や子にアタッチされているなんてことはないですよね?
個人的には、buttonMessageTextはGameObject型ではなくText型にしたほうが、GetComponent()を省略でき、Textが存在しないものを設定することを防げますので、こちらのほうがいいのではないかと思います。
UIのオブジェクトがbutton meshみたいなものしかなく、それが通常のbuttonだと勘違いしていました。
なので、textの方もmesh proの付いているものを使用していました。確認不足でした。
GetComponent<TextMeshProUGUI>()で解決しました。
ご指摘ありがとうございました。Textを意識的に使用していこうと思います。
回答1件
あなたの回答
tips
プレビュー