c# - 如何查找文件夹中的所有可编写脚本的对象,然后从其中加载变量?

标签 c# unity-game-engine scriptable-object

我的 Unity 项目中的“Resources/ScriptableObjects/Skins”下有一个文件夹。我需要获取文件夹中的所有对象,为索引生成一个随机数,然后将 Sprite 分配给脚本附加到的现有游戏对象。我收到的当前错误是第 151 行的“NullReferenceException:对象引用未设置为对象的实例”,但我正在第 149 行创建该对象的实例。这是我的函数,用于将文件夹中随机可脚本对象中的 Sprite 分配给脚本所绑定(bind)的游戏对象:

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。这只会创建 Assets 的克隆,但您不需要它。

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

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


我很确定它应该是

// 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;

关于c# - 如何查找文件夹中的所有可编写脚本的对象,然后从其中加载变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65400623/

相关文章:

c# - 如何在 Xamarin Forms 中制作卡片样式的 ListView

iphone - vuforia 和 uinavigationcontroller

c# - 如何在更改值后在运行时保存 ScriptableObject

c# - Java 中可以通过引用传递参数吗?

c# - Generic 类型参数前的 "out"是什么意思?

c# - 将空 String 反序列化为 List<string>

c# - 统一2D : animator single frame animations - instant transition

unity-game-engine - 确定碰撞发生在哪个碰撞器上

unity-game-engine - Unity ScriptableObjects - 只读字段

c# - 从一个保存文件反序列化多个不相关的 ScriptableObjects