小编Its*_*arv的帖子

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

我的统一项目中的“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>();

}
Run Code Online (Sandbox Code Playgroud)

这是可编写脚本的对象:

using UnityEngine;

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

c# unity-game-engine scriptable-object

2
推荐指数
1
解决办法
8891
查看次数

标签 统计

c# ×1

scriptable-object ×1

unity-game-engine ×1