I have a variable (randomPrefab) that is equal to a function that uses a scriptable object to randomly select them from a list in the Resources folder, however sometimes when the game is played in unity I'm getting an error that the randomPrefab variable is returning null. I am not sure why as it should be finding the same object each time.
Calling the function:
public void SpawnHeroes()
{
var heroCount = 1;
for (int i = 0; i < heroCount; i++)
{
var randomPrefab = GetRandomUnit<BaseHero>(Faction.Hero);
print(randomPrefab);
var spawnedHero = Instantiate(randomPrefab);
var randomSpawnTile = GridManager.instance.GetHeroSpawnTile();
randomSpawnTile.SetUnit(spawnedHero);
}
}
The function in question:
private T GetRandomUnit<T>(Faction faction) where T : BaseUnit {
return (T)units.Where(u => u.Faction == faction).OrderBy(o => Random.value).First().UnitPrefab;}
The scriptable unit code:
using UnityEngine;
[CreateAssetMenu(fileName = "New Unit", menuName = "Scriptable Unit")]
public class ScriptableUnit : ScriptableObject
{
public Faction Faction;
public BaseUnit UnitPrefab;
}
public enum Faction
{
Hero = 0,
Enemy = 1
}