我有一个生成器,每次我按下(1)键时就会生成一个球,每个球都会被存储在一个名为”targetBall“的Gameobjects数组中。我有一个AI玩家,它使用Move()方法来排斥球,但问题是AI玩家只能看到数组中的第一个球,即代码中显示的球[0],我该如何让AI玩家看到所有生成的球(无限个球)?我尝试使用for循环但没有成功(注意:其他一切都运行得很完美)
void Move() { targetBall = GameObject.FindGameObjectsWithTag("HokeyBall"); if (targetBall[0].GetComponent<HokyBall>().ballDirection == Vector3.right) { ballPos = targetBall[0].transform.localPosition; if (transform.localPosition.x < Lboundry && ballPos.x > transform.localPosition.x) { transform.localPosition += new Vector3(speed * Time.deltaTime, 0, 0); } if (transform.localPosition.x < Lboundry && ballPos.x < transform.localPosition.x) { transform.localPosition += new Vector3(-speed * Time.deltaTime, 0, 0); } }}
这是我尝试使用for循环查找每个生成的球的方法,但出现了错误(无法将“int”转换为“GameObject”)
void Move() { targetBall = GameObject.FindGameObjectsWithTag("HokeyBall");foreach (GameObject i in targetball){ if (targetBall[i].GetComponent<HokyBall>().ballDirection == Vector3.right) { ballPos = targetBall[i].transform.localPosition; if (transform.localPosition.x < Lboundry && ballPos.x > transform.localPosition.x) { transform.localPosition += new Vector3(speed * Time.deltaTime, 0, 0); } if (transform.localPosition.x < Lboundry && ballPos.x < transform.localPosition.x) { transform.localPosition += new Vector3(-speed * Time.deltaTime, 0, 0);} } } }
回答:
foreach
返回集合中的对象,因此你无法访问该集合。
使用foreach的方法 –
void Move() { targetBall = GameObject.FindGameObjectsWithTag("HokeyBall"); foreach (GameObject go in targetball) { if (go.GetComponent<HokyBall>().ballDirection == Vector3.right) { ballPos = go.transform.localPosition; if (transform.localPosition.x < Lboundry && ballPos.x > transform.localPosition.x) { transform.localPosition += new Vector3(speed * Time.deltaTime, 0, 0); } if (transform.localPosition.x < Lboundry && ballPos.x < transform.localPosition.x) { transform.localPosition += new Vector3(-speed * Time.deltaTime, 0, 0); } } } }
使用for循环的方法 –
void Move() { targetBall = GameObject.FindGameObjectsWithTag("HokeyBall"); for (int i = 0; i < targetBall.Length; i++) { if (targetBall[i].GetComponent<HokyBall>().ballDirection == Vector3.right) { ballPos = targetBall[i].transform.localPosition; if (transform.localPosition.x < Lboundry && ballPos.x > transform.localPosition.x) { transform.localPosition += new Vector3(speed * Time.deltaTime, 0, 0); } if (transform.localPosition.x < Lboundry && ballPos.x < transform.localPosition.x) { transform.localPosition += new Vector3(-speed * Time.deltaTime, 0, 0); } } } }