#状況
シーン上には
・Button1
・Button2
・Button3
という3つのオブジェクトがある。
Button1にアタッチしたスクリプトで、String変数”Type"で条件分岐し「指定されたURLへリクエストを送って自身のテクスチャを変更する」「子要素のマテリアルの色を指定の色に変更する」という処理を行なうコルーチンを定義した。
これをUpdate()内で呼んで実行したところ、期待通り動作した。
他のButtonもButton1と同じように色やテクスチャ画像を変更したいが、条件分岐の処理はまとめてどこかに置いておきたいので(でないと分岐が一つ加わると全部変えないといけない)、他のオブジェクトではこのスクリプトに書いた同一のコルーチンを呼び出す形で使いたい。
#試したこと
とりあえず、Button2にアタッチするスクリプトでpublic Button1Script button1Script
として、UnityのGUI上でオブジェクトを紐付けた上で、Update()内で StartCoroutine(button1Script.myCoroutine());
という形で呼んでみたところ、
NullReferenceException: Object reference not set to an instance of an object
と言われた。
#書いたコード抜粋
Button1Script
C#
1public IEnumerator myCoroutine() 2 { 3 bool once = true; 4 string url; 5 Texture2D tex; 6 Color32 color; 7 8 if (once) 9 { 10 if (type == "twitter") 11 { 12 url = "hoge"; 13 color = new Color32(29, 161, 250, 255); 14 } 15 else if (type == "facebook") 16 { 17 url = "hogehoge"; 18 color = new Color32(36, 119, 241, 255); 19 } 20 else 21 { 22 url = ""; 23 color = new Color32(0, 0, 0, 0); 24 } 25 26 27 var request = UnityWebRequestTexture.GetTexture(url); 28 yield return request.Send(); 29 tex = new Texture2D(4, 4, TextureFormat.DXT1, false); 30 31 tex.LoadImage(request.downloadHandler.data); 32 GetComponent<Renderer>().material.mainTexture = tex; 33 cylinder.GetComponent<Renderer>().material.color = color; 34 once = false; 35 yield break; 36 } 37 } 38 39 // Update is called once per frame 40 void Update() 41 { 42 type = "hogehoge";//こちらも別スクリプトから取得してきた変数 43 44 StartCoroutine(myCoroutine()); 45 46 }
Button2Script
C#
1public Button1Script button1Script;//GUIでできたエリアにhierarchyからButton1を突っ込む 2void Update(){ 3type = "hogehogehoge"; 4StartCoroutine(button1Script.myCoroutine());//エラーメッセージ発生箇所
#教えていただきたいこと
Button2Scriptで、これに近い形でコルーチンを呼び出す方法はありますでしょうか?
もし難しそうであれば、「これならいける」という方法をご教授いただけますでしょうか。
散々調べたのですがどうも適切そうな文献が見当たらず。
まだ未熟で稚拙な質問となってしまったかもしれませんが、何卒よろしくお願いいたします!
もし追加で必要な情報等ありましたら迅速に対応させていただきますのでお申し付けくださいませ。
回答1件
あなたの回答
tips
プレビュー