前提・実現したいこと
UnityC#についての相談です。
家と学校に見立てた四角形(順にHome,School)を、人に見立てたボール(Human)が行き来するというスクリプトを目指しています。
具体的には、以下のようなものを目指しています。
・HumanとHomeのプレハブを1から始まる連番で、どちらも同じ座標に生成。
・Vector3型のListであるhuman、homeを宣言し、生成されたHumanとHomeの初期座標をそれぞれ代入(human[0]にはHuman1の座標のように)
・Humanは、左クリックの後、Humanと同じ連番を振ったHome(Human1ならHome1というように)からSchoolの座標に向かう。
・その後、右クリックで、今度は同じ連番を振ったHomeの座標に戻ってくる。
しかし、色々試してみたものの、どのようにして初期座標を代入するか、悩んでいます。
どうか知恵をお貸しいただけませんでしょうか。
よろしくお願いいたします。
今までのスクリプトは以下の通りです。
発生している問題・エラーメッセージ
NullReferenceException: Object reference not set to an instance of an object
HumanMover.Update () (at Assets/HumanMover.cs:36)
該当のソースコード
C#
1<ObjectMaker.cs>========== 2using System.Collections; 3using System.Collections.Generic; 4using UnityEngine; 5 6public class ObjectMaker : MonoBehaviour { 7 8 public GameObject Home; 9 public GameObject Human; 10 11 public GameObject HomeClone; 12 public GameObject HumanClone; 13 14 public int homenumber = 1; 15 public int humannumber = 1; 16 17 void Update () { 18 19 if (Input.GetMouseButtonDown(0)) 20 { 21 GameObject HomeClone = Instantiate(Home, new Vector3(Random.Range(40.0f, 45.0f), 0.5f, Random.Range(40.0f, 45.0f)), Quaternion.identity); 22 GameObject HumanClone = Instantiate(Human, HomeClone.transform.position, Quaternion.identity); 23 24 HomeClone.name = "Home" + homenumber; 25 HumanClone.name = "Human" + humannumber; 26 27 homenumber += 1; 28 humannumber += 1; 29 } 30 } 31} 32<HumanMover.cs>========== 33using System.Collections; 34using System.Collections.Generic; 35using UnityEngine; 36 37public class HumanMover : MonoBehaviour 38{ 39 40 public GameObject ObjectMaker; 41 42 GameObject Human; 43 44 GameObject Home; 45 46 GameObject School; 47 48 public List<Vector3> human = new List<Vector3>(); 49 public List<Vector3> home = new List<Vector3>(); 50 51 int arraynumber = 0; 52 53 void Update() 54 { 55 if (Input.GetMouseButtonDown(0)) 56 { 57 GameObject ObjectMaker = GameObject.Find("ObjectMaker"); 58 59 int humannumber = ObjectMaker.GetComponent<ObjectMaker>().humannumber; 60 int homenumber = ObjectMaker.GetComponent<ObjectMaker>().homenumber; 61 62 human[arraynumber] = GameObject.Find("Human" + humannumber).transform.position; 63 home[arraynumber] = GameObject.Find("Home" + homenumber).transform.position; 64 65 Vector3 school = GameObject.Find("School").transform.position; 66 67 transform.localPosition = Vector3.MoveTowards(human[arraynumber], school, Time.deltaTime * 3.0f); 68 69 } 70 71 if (Input.GetMouseButtonDown(1)) 72 { 73 transform.localPosition = Vector3.MoveTowards(human[arraynumber], home[arraynumber], Time.deltaTime * 3.0f); 74 } 75 76 arraynumber += 1; 77 } 78} 79========================
試したこと
human、homeをListとして宣言して、その配列にGameObject.Find関数で探したHuman、Homeの初期座標を代入しようとしました。
補足情報(FW/ツールのバージョンなど)
Visual Studio 2017
Unity 2018.1.0b1
回答1件
あなたの回答
tips
プレビュー