I’m using Unity 2017.3.1f1 and when following the tutorial to check if all the enemies are dead, the code reports true constantly. I’ve looked over and over again and can’t see what I’ve done wrong or why it’s always showing as true, even when I have just restarted the scene and the screen is full of enemies.
// Use this for initialization
void Start ()
{
// Calculate the Boundary of the screen
float distanceToCamera = transform.position.z - Camera.main.transform.position.z;
Vector3 leftBoundary = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, distanceToCamera));
Vector3 rightBoundary = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, distanceToCamera));
maxX = rightBoundary.x;
minX = leftBoundary.x;
// Loop through every item in the collection to create an enemy on the positions.
foreach (Transform child in transform)
{
GameObject enemy = Instantiate(enemyPrefab, child.transform.position, Quaternion.identity) as GameObject;
enemy.transform.parent = child;
}
}
public void OnDrawGizmos()
{
Gizmos.DrawWireCube(transform.position, new Vector3(width, height, 0));
}
// Update is called once per frame
void Update()
{
// Check if the formation is going outside of the play space.
float rightEdgeOfFormation = transform.position.x + (0.5f * width);
float leftEdgeOfFormation = transform.position.x - (0.5f * width);
// Set the formation to move left or right between the limits of the edges
if (movingRight)
{
transform.position += Vector3.right * speed * Time.deltaTime;
}
else
{
transform.position += Vector3.left * speed * Time.deltaTime;
}
// Switch the direction of the formation
if (leftEdgeOfFormation < minX)
{
movingRight = true;
}
else if (rightEdgeOfFormation > maxX)
{
movingRight = false;
}
if (AllMembersDead())
{
Debug.Log("Empty formation!");
}
}
bool AllMembersDead()
{
foreach (Transform childPositionGameObject in transform)
{
if (childPositionGameObject.childCount > 0)
{
return false;
}
}
return true;
}
If I use
bool AllMembersDead()
{
foreach (Transform childPositionGameObject in transform)
{
if (childPositionGameObject.childCount > 0)
{
return false;
}
return true;
}
}
though then I get a compiler error that not all code paths return a value.
I’m banging my head against the desk trying to figure out where I’ve made the mistake and just can’t see it