c# - 如何控制数组中的所有游戏对象?
问题描述
我有一个生成器,每次按下 (1) 时都会生成一个球,每个球将存储在名为“ targetBall ”的游戏对象数组中,我有一个AI 玩家使用Move()方法击退球,但问题是AI 玩家只看到数组中的第一个球,即 ball [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);
}
}
}
}
对于循环 -
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);
}
}
}
}
推荐阅读
- amazon-web-services - 在 Amazon Redshift Spectrum 中加载外部表时如何跳过最后几条记录?
- r - 按组检查是否存在基于其他列的先前条目
- php - php数组合并重复发生
- ios - 新 PDF 中的 Rander PDFAnnotation
- mysql - MySQL查询以从表中输出带有列标题的数据
- python - 用于监控设备的 Python 脚本
- sql - SQL 根据其他值分组除以选择
- swift - 无法将场景编辑器中的 SKSpriteNode 引用到代码中
- c# - Asp.net 在 PostBack 后丢失所有信息
- php - 如何测试添加的图像是否适用于 WooCommerce 产品?