如何在一个文件夹中找到所有可编写脚本的对象,然后从中加载一个变量?

问题描述

我的 unity 项目中有一个文件夹位于“Resources/ScriptableObjects/Skins”下。我需要获取文件夹中的所有对象,为索引生成一个随机数,然后将精灵分配给脚本附加到的现有游戏对象。我得到的当前错误是第 151 行的“NullReferenceException:对象引用未设置为对象的实例”,但我正在第 149 行创建对象的实例。是什么给出了?这是我的函数,用于将来自文件夹中随机脚本对象的精灵分配给脚本绑定到的游戏对象:

void AssignRandomSkin(){
    // Load all skins into memory
    Object[] skinObjects = Resources.LoadAll("ScriptableObjects/Skins");


    // Get length of list
    int amountOfSkins = skinObjects.Length;

    // Get random index of skin to assign
    int skinToAssignIndex = Random.Range(0,amountOfSkins);

    GameObject thisSkin = Instantiate(skinObjects[skinToAssignIndex]) as GameObject;
    // Assign it to game object
    gameObject.GetComponent<SpriteRenderer>().sprite = thisSkin.GetComponent<Sprite>();

}

这是可编写脚本的对象:

using UnityEngine;

[CreateAssetMenu(fileName = "Skin",menuName = "ScriptableObjects/SkinObject",order = 1)]
public class SkinObject : ScriptableObject
{
    public string spriteName; // Name of sprite

    public Sprite sprite;

    public float xPos;

    public float yPos;

    public float zPos;

    public float xScale;

    public float yScale;

    public float zScale;

    public float fallSpeed; //AKA Weight

    public string tier; //Category that skin can be assigned in
}

解决方法

那么这里发生了什么?

您的对象是 SkinObject 类型的 ScriptableObject! => 它们不是 GameObject 预制件!

您的代码中的所有内容都应该可以工作,直到

GameObject thisSkin = Instantiate(skinObjects[skinToAssignIndex]) as GameObject;

首先没有必要实例化一个 ScriptableObject。这只会创建资产的克隆,但您不需要它。

其次,您正试图将其转换为 GameObject。如前所述,这是一种类型不匹配,因此 thisSkin 将是 null

最后 Sprite 不是组件。您宁愿尝试访问您的 .sprite 类型的字段 SkinObject


我很确定它应该是

// You can directly tell LoadAll to only load assets of the correct type
// even if there would be other assets in the same folder
SkinObject[] skinObjects = Resources.LoadAll<SkinObject>("ScriptableObjects/Skins");

var thisSkin = skinObjects[Random.Range(0,skinObjects.Length)];
// Assign it to game object
gameObject.GetComponent<SpriteRenderer>().sprite = thisSkin.sprite;

但是,如前所述,从 Best Practices - Resource Folder 不要使用它!

为什么不通过像这样的字段中的 Inspector 以通常的方式简单地引用这些 ScriptableObjects

public SkinObject[] availableSkins;