Reputation: 367
In unity I am using a script to randomly create enemies that attack your player. To do this I need to insert a game object, add a SpriteRenderer, name it, and then give it a texture which is in assets.
Here is my code:
GameObject sprGameObj = new GameObject();
sprGameObj.AddComponent<SpriteRenderer>();
sprGameObj.name = "Enemy";
sprGameObj.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("EnemyImage");
The code inserts a game object, adds the sprite renderer and names it however does not add the image "EnemyImage" to the sprite. I have looked online but everyone else is using code similar to mine which doesn't work either.
Does anyone know a solution?
I am coding in C#.
Update:
I tried putting this code inside an already existing sprite and it just removed it's image:
gameObject.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("EnemyImage");
Could there be a problem with the image itself?
Upvotes: 4
Views: 9560
Reputation: 405
First of all, I`d recommend using some sort of config object for organized and name-independent storing of your assets. In that case you could register all used graphic files in that config and get the asset you need by calling something like 'Config.SpritesData.GetEnemySprite(EnemyType.Orc)' for example. But for now you can start by checking the path of your sprite in the Assets folder, because Resources.Load works with files in Resources folder only. If the path is right, asset import type also worth checking, because Load<>() method is casting it to a Sprite, so casting result may be null if your asset is not imported as a sprite. Let me know if you checked this two things and it still doesnt work, I'll give it some more thoughts.
Upvotes: 2