Hey all,
So I’m working on a game jam (mostly as a 3D artist/composer) and I’ve found myself digging deeper into the programming side of things lately. I have a ScriptableObject that has a list of encounter prefabs that spawn in the overworld, and each has a percentage chance to spawn, which in total add up to 100. In the ScriptableObject it then creates an array (weights[100]) that iterates each encounter to however many indeces their spawn chance indicates (so if encounter 1 had a 30% chance, weights[0 to 29] would point to that prefab and so on).
Within the overworld script, the game picks a random number between 0 and 99 and instantiates the index of weights associated with that number. I do have a spawn timer that swaps out the prefab at regular intervals (not sure if I want to keep that part or just have it spawn once on scene load). This works fine until switching to the combat scene and coming back to the overworld, where spawnedEncounter comes up as missing and it can’t seem to re-initialize it. I’ve tried a number of things to remedy this but I’m kind of stumped.
It’s worth noting that no errors or exceptions come up at runtime, it just simply stops working as soon as I leave the initial scene. Anyone have any ideas?
Here is a sample of my code:
public CombatEncounterSpawner encounters;
public GameObject spawnedEncounter = null;
private int length;
public float spawnTimer;
private float timer;
public float positionOffset;
public bool isSpawned;
void Awake()
{
timer = spawnTimer;
}
void Update()
{
if (timer >= spawnTimer)
{
StartCoroutine(DestroySpawn());
StartCoroutine(SpawnCombatEncounter());
timer = 0f;
}
timer += Time.deltaTime;
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, positionOffset);
}
IEnumerator SpawnCombatEncounter()
{
if (isSpawned == false)
{
spawnedEncounter = Instantiate(encounters.weights[UnityEngine.Random.Range(0,99)], new Vector3(
transform.position.x + UnityEngine.Random.Range(-positionOffset,positionOffset),
transform.position.y,
transform.position.z + UnityEngine.Random.Range(-positionOffset,positionOffset)),
Quaternion.identity);
spawnedEncounter.transform.parent = this.transform;
isSpawned = true;
}
yield return null;
}
IEnumerator DestroySpawn()
{
Destroy(spawnedEncounter);
isSpawned = false;
yield return null;
}