5

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;

It did not work, however this worked (used <Sprite>):

GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("GameObjects/Tiles/Hole");

What's the difference?

maZZZu
  • 3,585
  • 2
  • 17
  • 21
Ferenc Dajka
  • 1,052
  • 3
  • 17
  • 45
  • 1
    Do you have multiple files in your project named "Hole"? The one command specifies an asset type to search for, but the other does not. Depending on your file structure, they might be looking up different results because of that. – rutter Feb 20 '15 at 18:09

2 Answers2

4

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.

In other words, you can't use as Sprite because you cannot cast a Texture2D to a Sprite. You CAN, however, use

Texture2D texure = Resources.Load("GameObjects/Tiles/Hole");
Rect rect        = {whatever};
Vector2 pivot    = {whatever};

Sprite.Create(texture, rect, pivot);

but this requires you to know the size of the Sprite you were trying to load.

In summary, Load() treats it based solely on the file type you're loading, Load<T>() includes metadata.

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Mars
  • 2,505
  • 17
  • 26
3
Resources.Load("GameObjects/Tiles/Hole") as Sprite;

You have another "Hole" in your Resources folder. This other-Hole is not a Sprite. Therefore when you use as Sprite it simply can't be casted to one and won't throw an exception (on that line) because:

The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.


Resources.Load<Sprite>("GameObjects/Tiles/Hole");

In the working code you specify which file you want, the Sprite, so it finds the correct one.

apxcode
  • 7,696
  • 7
  • 30
  • 41
  • In the Windows Explorer I have one file called **Hole.png**, and an other called **Hole.png.meta** if I **Debug.Log(Resources.Load("GameObjects/Tiles/Hole"));** then it's a **Sprite** and if I **Debug.Log((Resources.Load("GameObjects/Tiles/Hole")));** then it's a **Texture2D**.. So the **.meta** file is a Texture2D file? In the Unity Project explorer however I have only one Resource file called Hole. – Ferenc Dajka Feb 24 '15 at 09:04