I have a generator which generate a ball every time I press (1) , each ball will be stored in Array of Gameobjects called "targetBall" , I have an AI player which repels the ball with Move() method, but the problem is the AI player see only the first ball in array which is ball [0] as shown in code , how I can make the AI player see all the generated ball (infinite balls) , I tried to use for loop but I didn't make it (note : every thing worked perfect)
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);
}
}
}
and this is my attempt to find each ball generated using for loop , and give me error (cant convert "int" to "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);
}
}
}
}
CodePudding user response:
foreach
returns object from the collection, so you don't have access to that collection.
Foreach way -
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 loop -
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);
}
}
}
}