Hi everyone, I’m currently learning Unity and following the unity tutorial for lesson 2.4.
One issue I’ve run into is that when my original object go out of bounds and is destroyed, they no longer spawn the prefabs and gives me a “MissingReferenceException”. Also in the inspector tab for my RandomSpawn script, element 0, 1, and 2 shows "Missing (Game Object). All of my prefabs also contain the same scripts as the original object as well. I’m following the tutorial and doing it exactly how they do it and it seems to work for them but it does not run properly for me and I’m not too sure why.
Any help would be appreciated.
Here is my code for the RandomSpawn script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomSpawn : MonoBehaviour
{
public GameObject[] animalArray; //create a game object array to hold 3 animal prefabs.
private float lowerSpawnBound_X = -12.61f;
private float upperSpawnBound_X = 15.33f;
private float spawn_z_Position = 18.38f;
private float startTime = 2f; //initial time before first spawn
private float repeatTime = 1.5f; //spawn every 2s after
// Start is called before the first frame update
void Start()
{
//spawn the animals on a timer.
InvokeRepeating("spawnRandomAnimal", startTime, repeatTime); //Calls the method for the first time after 'x' seconds, and then repeats the call every 'y' seconds after.
}
// Update is called once per frame
void Update()
{
}
private void spawnRandomAnimal() //giving error that object is already destroyed
{
int animalIndex = Random.Range(0, animalArray.Length);
Vector3 spawnPos = new Vector3(Random.Range(lowerSpawnBound_X, upperSpawnBound_X), 0, spawn_z_Position);
Instantiate(animalArray[animalIndex], spawnPos, animalArray[animalIndex].transform.rotation);
}
}