Unity Resources.Load< Sprite>与雪碧 [英] Unity Resources.Load<Sprite> vs as Sprite
问题描述
我尝试使用以下代码(使用作为Sprite 强制转换)更改对象的图像:
I've tried to change the image of my object with this code (used as Sprite cast):
GetComponent<SpriteRenderer>().sprite = Resources.Load("GameObjects/Tiles/Hole") as Sprite;
它不起作用,但是起作用了(使用< Sprite> ):
It did not work, however this worked (used <Sprite>):
GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("GameObjects/Tiles/Hole");
有什么区别?
推荐答案
FunctionR的答案可能是更常见的答案,在这里我可能是错的,但是我相信Load()
和Load<T>()
之间的区别是Load<T>()
检查元数据. 孔"不是Sprite
,而是图像文件. Load()
查找该图像文件并将其作为文件类型的默认类型(在本例中为Texture2D
)加载.
FunctionR's answer is probably the more common answer, and I may just be wrong here, but I believe the difference between Load()
and Load<T>()
is that Load<T>()
checks for meta-data. "Hole" is not a Sprite
, it's an image file. Load()
finds that image file and loads it as it's default type for the file type, in this case Texture2D
.
换句话说,您不能使用as Sprite
,因为您不能cast
将Texture2D
转换为Sprite
.您可以使用
In other words, you can't use as Sprite
because you cannot cast
a Texture2D
to a Sprite
. You CAN, however, use
Texture2D = Resources.Load("GameObjects/Tiles/Hole");
Rect rect = {whatever};
Vector2 pivot = {whatever};
Sprite.Create(texture, rect, pivot);
但这需要您知道您要加载的Sprite
的大小.
but this requires you to know the size of the Sprite
you were trying to load.
总而言之,Load()
仅根据您正在加载的文件类型对其进行处理,Load<T>()
包括元数据.
In summary, Load()
treats it based solely on the file type you're loading, Load<T>()
includes metadata.
这篇关于Unity Resources.Load< Sprite>与雪碧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!