I have 3 rocks as prefabs on Unity, I attached this code to the camera and added them as the Rock Prefabs.
The idea is that I create 3 rocks, and wait until they are out of the screen, and every time I destroy 1, create a new one. The thing is that the onBecameInvisible method is never accessed. What am I doing wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class createRock : MonoBehaviour
{
// Object
[SerializeField]
GameObject rockPrefab;
// spawn control
const float MinSpawnDelay = 1;
const float MaxSpawnDelay = 2;
Timer spawnTimer;
float allowedRocks = 2;
private GameObject[ ] numberOfRocks;
// spawn location support
const int SpawnBorderSize = 100;
int minSpawnX;
int maxSpawnX;
int minSpawnY;
int maxSpawnY;
///
/// Use this for initialization
///
void Start()
{
// save spawn boundaries for efficiency
minSpawnX = SpawnBorderSize;
maxSpawnX = Screen.width - SpawnBorderSize;
minSpawnY = SpawnBorderSize;
maxSpawnY = Screen.height - SpawnBorderSize;
//Check the amount of rocks
// create and start timer
spawnTimer = gameObject.AddComponent();
spawnTimer.Duration = Random.Range(MinSpawnDelay, MaxSpawnDelay);
spawnTimer.Run();
}
///
/// Update is called once per frame
///
void Update()
{
// check for time to spawn a new rock
numberOfRocks = GameObject.FindGameObjectsWithTag(“rockCreated”);
if (numberOfRocks.Length <= allowedRocks && spawnTimer.Finished)
{
//print("The Number of rocks is " + numberOfRocks.Length);
createAnotherRock();
// change spawn timer duration and restart
spawnTimer.Duration = Random.Range(MinSpawnDelay, MaxSpawnDelay);
spawnTimer.Run();
}
}
/// Spawns a new rock at a random location
void createAnotherRock()
{
// generate random location and create new rock
Vector3 location = new Vector3(Random.Range(minSpawnX, maxSpawnX),
Random.Range(minSpawnY, maxSpawnY),
-Camera.main.transform.position.z);
Vector3 worldLocation = Camera.main.ScreenToWorldPoint(location);
GameObject rock = Instantiate(rockPrefab) as GameObject;
rock.transform.position = worldLocation;
}
void OnBecameInvisible()
{
Destroy(this.gameObject);
}
}