“ assets / resource / mat”中有一些图像。我想获取此图像并将其放置到array中。但是当我尝试获取这些图像时,我得到了ArrayIndexOutOfBoundsException。我认为Resource.LoadAll(“ mat”)方法存在问题。但是我无法解决。请帮助我
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class test : MonoBehaviour
{
private string t;
public Sprite[] Icons;
void Start()
{
Object[] loadedIcons = Resources.LoadAll("mat");
Icons = new Sprite[loadedIcons.Length];
for (int x = 0; x < loadedIcons.Length; x++)
{
Icons[x] = (Sprite)loadedIcons[x];
Debug.Log("Loading....");
}
GameObject sp = new GameObject();
sp.GetComponent<SpriteRenderer>().sprite = Icons[0];
}
}
答案 0 :(得分:0)
使用LINQ从特定文件夹加载所有图像看起来像这样...
using UnityEngine;
using System.Linq;
public class Four : MonoBehaviour
{
public Sprite[] icons;
void Start()
{
icons= Resources.LoadAll("met", typeof(Sprite)).Cast<Sprite>().ToArray();
}
}
答案 1 :(得分:0)
我不确定,但是我想您不是必须先加载Sprite
而不是Texture2D
,然后再从中创建一个Sprite
。
还请注意,您在新创建的空GameObject上使用了GetComponent<SpriteRenderer>()
,因此显然不会附加任何SpriteRenderer
组件。而是使用AddComponent
。
Sprite[] Icons;
Texture2D LoadedTextures;
private void Start()
{
LoadedTextures = (Texture2D[])Resources.LoadAll("mat", typeof(Texture2D));
Icons = new Sprite[loadedIcons.Length];
for (int x = 0; x < loadedIcons.Length; x++)
{
Icons[x] = Sprite.Create(
LoadedTextures[x],
new Rect(0.0f, 0.0f, LoadedTextures[x].width, LoadedTextures[x].height),
new Vector2(0.5f, 0.5f),
100.0f);
}
GameObject sp = new GameObject();
// Note that here you created a new empty GameObject
// so it obviously won't have any component of type SpriteRenderer
// so add it instead of GetComponent
sp.AddComponent<SpriteRenderer>().sprite = Icons[0];
}