Improving script which Spawns enemies up to a required number
This script I have written spawns fish up to a required number and upholds that number of fish in the scene, respawning more up to the number when fish get destroyed.
Could anyone offer some improvements on it? How can I make it run faster?
using UnityEngine;
using System.Collections;
public class randomFish : MonoBehaviour {
public GameObject[] fish; // this is where all the spawned fish are held
public int maxAmountOfFish; // wanted maximum amount of fish in scene
private int amount; // amount of fish in GameObject[] fish
private Vector3 spawnPoint; // spawn point of fish
private int randomFishNumber; // number of prefab selected to be cloned at random
public GameObject fishClone;
void Update ()
{
GameObject[] fish = GameObject.FindGameObjectsWithTag ("fish");
amount = fish.Length; // the amount of fish in the scene is the length of the array called "fish"
if (amount != maxAmountOfFish) {
InvokeRepeating ("Spawn", 1, 60f);
}
}
void Spawn ()
{
spawnPoint.x = Random.Range (-2.5f, -5.0f); // spawn points to spawn from
spawnPoint.y = Random.Range (-0.8f, -0.5f);
spawnPoint.z = Random.Range (-5.0f, 5.0f);
randomFishNumber = Random.Range (1, 6); // random fish 1-5 (6 excluded)
fishClone = Resources.Load ("FishPrefabs/SALMON" + randomFishNumber) as GameObject;
Debug.Log (fishClone);
fishClone = Instantiate (fishClone, spawnPoint, Quaternion.identity) as GameObject;
fishClone.tag = "fish";
CancelInvoke();
}
}
If you are helding all fish in global array, why do you need fish array in Update()?
I need to update the array to check how many fish have been spawned into the array, to know how many fish are in the scene so the constant maximum number is upheld if a couple get destroyed, although there may be a better way of doing this?
Do you need to make it run faster? While there are some $$anonymous$$or ways to improve the performance (cache the loaded prefabs, maintain an array of fish rather than finding them by tag every frame), there is not much you can do here. Until you have profiled your game and found out that this code is causing a problem, don't waste too much time trying to make it faster.
I'm just trying to learn how to make my scripting better as a beginner, I'm sure I'm doing some elementary mistakes in the eyes of the proficient so I ask :) Caching loaded prefabs isn't something I've looked into (and probably should because I don't know what it does) so thank you for pointing that out to me!
I'm not sure I can maintain an array without update as I'm destroying and spawning fish tagged "fish"? $$anonymous$$y understanding is if I don't check it in update then it won't check the number, although I could put this under an InvokeRepeating and check every three seconds perhaps?