C# 如何在文件夹中找到所有可编写脚本的对象,然后从其中加载变量?
我在unity项目的“Resources/ScriptableObjects/Skins”下有一个文件夹。我需要获得文件夹中的所有对象,为索引生成一个随机数,然后将精灵分配给脚本附加到的现有游戏对象。我当前遇到的错误是第151行的“NullReferenceException:对象引用未设置为对象的实例”,但我正在第149行创建对象的实例。有什么好处?下面是我的函数,用于将文件夹中随机scriptableobject中的精灵分配给脚本绑定到的游戏对象:C# 如何在文件夹中找到所有可编写脚本的对象,然后从其中加载变量?,c#,unity3d,scriptable-object,C#,Unity3d,Scriptable Object,我在unity项目的“Resources/ScriptableObjects/Skins”下有一个文件夹。我需要获得文件夹中的所有对象,为索引生成一个随机数,然后将精灵分配给脚本附加到的现有游戏对象。我当前遇到的错误是第151行的“NullReferenceException:对象引用未设置为对象的实例”,但我正在第149行创建对象的实例。有什么好处?下面是我的函数,用于将文件夹中随机scriptableobject中的精灵分配给脚本绑定到的游戏对象: void AssignRandomSkin
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>();
}
那么这里发生了什么
您的对象是ScriptableObject类型的SkinObject
!=>它们不是游戏对象预制的
代码中的所有内容都应该工作到
GameObject thisSkin = Instantiate(skinObjects[skinToAssignIndex]) as GameObject;
首先,没有必要实例化ScriptableObject
。这只会创建资产的克隆,但您不需要它
第二步,您尝试将其投射到GameObject
。如上所述,这是一种类型不匹配,因此thiskin
将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;
我们看不出哪一行是152和149-您是否介意编辑您的问题,以包括您使用的方法或以某种方式标记的方法?抱歉,这是149。GameObject thisSkin=实例化(skinObjects[skinToAssignIndex]),这是152 GameObject.GetComponent().sprite=thisSkin.GetComponent(),一般来说:为什么?我是说。。为什么呢?不要用它。。。为什么不在
public SkinObject skin这样的字段中通过检查器简单地引用这些scriptableobject代码>?或者从数组public SkinObject[]availableSkins中随机选择一个代码>因为我必须写一个对每个皮肤的引用,而且会有很多。我只想把所有的对象放在一个位置,然后随机挑选一个对象,注意,把它作为一个游戏对象来产生是没有意义的。。。它是一个皮肤对象
。。。而且没有这样的组件Sprite
。。。您更希望访问字段。sprite
不确定该解决方案是否有效。我深入研究了你关于不使用资源文件夹的评论,并决定放弃这个想法。我现在使用您的建议声明一个公共SkinObject[]skinsAvailable数组。然后,我从对象获取随机皮肤的代码是gameObject.GetComponent().sprite=availableSkins[skinToAssignIndex].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;
public SkinObject[] availableSkins;