Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSean Gwall
984 PointsNo new flies spawning?
After I collect a fly in the game, a new one won't respawn?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class FlySpawner : MonoBehaviour {
// Variables
[SerializeField]
private GameObject flyPrefab;
[SerializeField]
private int totalFlyMinimum = 12;
[SerializeField]
private float spawnArea = 25f;
public static int totalFlies;
// Use this for initialization
void Start () {
totalFlies = 0;
//While the total number of flies is less then the minimum...
while (totalFlies < totalFlyMinimum) {
// Add 1 to totalFlies
totalFlies++;
// Create a random position for a fly
float positionX = Random.Range(-spawnArea, spawnArea);
float positionZ = Random.Range(-spawnArea, spawnArea);
Vector3 flyPosition = new Vector3 (positionX, 2f, positionZ);
// Create a new fly
Instantiate(flyPrefab, flyPosition, Quaternion.identity);
}
}
// Update is called once per frame
void Update () {
}
}
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class FlyPickup : MonoBehaviour {
[SerializeField]
private GameObject pickupPrefab;
void OnTriggerEnter(Collider other) {
// If the collider other is tagged with "Player"
if (other.CompareTag ("Player")) {
// Add the pickup particules
Instantiate(pickupPrefab, transform.position, Quaternion.identity);
// Remove 1 from the total number of flies
FlySpawner.totalFlies--;
Destroy (gameObject);
}
}
}
nathanmendes
6,929 Pointsnathanmendes
6,929 PointsHey, I'm replying to this long after you posted it, but I'll reply just in case. All you need to do is move your while loop in your FlySpawner script from the start method to the update method. Otherwise the code is only calling the while loop once at the beginning of the game and not checking up again on the variables as the game progresses. Hope this helps!