Question by
eriknastesjo · Dec 27, 2019 at 05:25 PM ·
gameobjectarrayclosest
How to check if there are no more objects in array (with conditions)
Hi! In my game there are several balls and a paddle. I use the code below to find the ball closest to the paddle (and the paddle is moving towards it). I only want the paddle to detect balls going towards left and ignore the once going towards right. Problem is when there are no balls going towards left I get error messages "NullReferenceException: Object not set to an instance of an object". Have tried to set conditions and bools to make the paddle get that there are no balls to find but then I get other bugs. Help is much appreciated!
void FindClosestBall()
{
float distanceToClosestBall = Mathf.Infinity;
Ball closestBall = null;
Ball[] allBalls = GameObject.FindObjectsOfType<Ball>();
foreach (Ball currentBall in allBalls)
{
float distanceToBall = (currentBall.transform.position - this.transform.position).sqrMagnitude;
Rigidbody2D currentBallRigidbody = currentBall.GetComponent<Rigidbody2D>();
if (distanceToBall < distanceToClosestBall && currentBallRigidbody.velocity.x < 0f )
{
distanceToClosestBall = distanceToBall;
closestBall = currentBall;
}
}
if (transform.position.y < closestBall.transform.position.y) //ERROR MESSAGE REFERS TO THIS LINE! IN FIXEDUPDATE I SET THE MOVEMENT.
{
up = true;
down = false;
}
else if (transform.position.y > closestBall.transform.position.y)
{
down = true;
up = false;
}
else { up = false; down = false; }
}
Comment