最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

unity game engine - Referencing a Prefab only being found sometimes when the script is ran - Stack Overflow

programmeradmin0浏览0评论

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
}
发布评论

评论列表(0)

  1. 暂无评论