I was working on Create with Code Unit 5 and I did exactly what the instructor said in the videos. I ran my project and it looked good, but after a time the objects were getting deleted from the hierarchy and I can’t figure out how to keep all of the boxes spawning. To clarify, eventually all boxes get deleted and it cannot spawn any more. Here is some of my code. Any help is appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Target : MonoBehaviour
{
private Rigidbody targetRB;
private float minSpeed=12;
private float maxSpeed=16;
private float maxTorque=10;
private float xRange=4;
private float ySpawnPos=-2;
private SpawnManager spawnManager;
public int pointValue;
public ParticleSystem explosionParticle;
// Start is called before the first frame update
void Start()
{
targetRB = GetComponent<Rigidbody>();
targetRB.AddForce(randomForce(), ForceMode.Impulse);
targetRB.AddTorque(randomTorque(), randomTorque(), randomTorque(), ForceMode.Impulse);
transform.position=randomSpawnPos();
spawnManager=GameObject.Find("Spawn Manager").GetComponent<SpawnManager>;
}
// Update is called once per frame
void Update()
{
}
private void OnMouseDown(){
if (spawnManager.isGameActive){
Destroy(gameObject);
Instantiate(explosionParticle, transform.position, explosionParticle.transform.rotation);
spawnManager.UpdateScore(pointValue);
}
}
private void OnTriggerEnter(Collider other){
Destroy(gameObject);
if (!gameObject.CompareTag("Good")){
spawnManager.loseLife();
spawnManager.GameOver();
}
}
Vector3 randomSpawnPos(){
return new Vector3(Random.Range(-xRange,xRange),ySpawnPos);
}
float randomTorque(){
return Random.Range(-maxTorque,maxTorque);
}
Vector3 randomForce(){
return Vector3.up * Random.Range(minSpeed,maxSpeed);
}
}
And Here is my Spawn Manager Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class SpawnManager : MonoBehaviour
{
public List <GameObject> targets;
private float spawnRate=1.0f;
private int score;
public float lives;
public float objectsInPlay;
public bool isGameActive;
public TextMeshProUGUI scoreText;
public TextMeshProUGUI gameOverText;
public TextMeshProUGUI livesText;
// Start is called before the first frame update
void Start()
{
StartCoroutine(SpawnTarget());
score=0;
UpdateScore(0);
lives=5;
isGameActive=true;
}
IEnumerator SpawnTarget() {
while(true){
yield return new WaitForSeconds(spawnRate);
//Replace 3 with targets.Count
int index=Random.Range(0,3);
Instantiate(targets[index]);
objectsInPlay=objectsInPlay+1;
}
}
public void UpdateScore(int scoreToAdd){
score +=scoreToAdd;
scoreText.text="Score: "+score;
}
public void loseLife(){
lives=lives-1;
livesText.text="Lives: "+lives;
}
public void GameOver(){
gameOverText.gameObject.SetActive(true);
}
// Update is called once per frame
void Update()
{
}
}