[英]How to control all GameObjects in array?
我有一個生成器,每次按 (1) 時都會生成一個球,每個球都將存儲在名為“ targetBall ”的游戲對象數組中,我有一個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);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.