how can i write code to load a sprite dynamically from an resources in unity 2d @
Loads an asset stored at path in a Resources folder.
Returns the asset at path if it can be found otherwise returns null. Only objects of type will be returned if this parameter is supplied. The path is relative to any Resources folder inside the Assets folder of your project, extensions must be omitted.
class SpriteLoadFromAssest
{
private void Start()
{
//Load Sprite From The Resources Folder and use
var sp = Resources.Load("SpriteFolder/abc") as Sprite;
}
}
Okay, so I did everything the people above said and it didn’t work. after an hour of digging through forums, I finally found an answer that works for me. Here is what I did.
A: Inside of the Project Window, go to the Assets Folder, Right click on Assets and create new Folder
B: Name this new folder “Resources” …It may also be named “resources”
C: Take your image, or image folder and drag and drop these inside of the “Resources” folder.
D: right click on the image (that is a child of the “resources” folder) and left click on “copy path”
E: In your code type :: Sprite spriteName = Resources.Load(“Paste Code Here”);
F: in the above line, replace “Paste Code Here” with the copied path, for example, it should now read ::
Sprite spriteName = Resources.Load(“Assets/Resources/Images/MainScreenImages/EncountersQuests/Grey/Back/Grey02.png”);
G: remove the .png from the string, so it should be Assets/Resources/Images/MainScreenImages/EncountersQuests/Grey/Back/Grey02
H: remove the Assets/Resources/ from the string so it should be Images/MainScreenImages/EncountersQuests/Grey/Back/Grey02
I: The whole thing for my path (your path will most likely be very different) is now Sprite spriteName = Resources.Load(“Images/MainScreenImages/EncountersQuests/Grey/Back/Grey02”);
If your project is named MyProject, you have a folder called Assets
inside a folder called MyProject
that contents your whole Unity project.
First, if you don’t have a folder called Resources
inside Assets
, create it.
Then, you can create inside resources a folder only for sprites. This is optional, but highly useful to keep things in its proper place. In this example, we create the folder Sprites
inside Resources
.
Now, we put inside Sprites
an image called my_sprite.png
(.png
is actually the extension of a PNG image file).
So, in C#
you would do:
Sprite sp = Resources.Load<Sprite>("Sprites/my_sprite");
In Unity Script
(AKA Javascript), I don’t think you can parametrize types this way, so, @SohailBukhari’s approach should work for Javascript but I don’t know actually. I switched long ago from using Unity’s Javascript in favor of C#, and I’m glad I did.
can u pls explain clearly about what im posted a question because im a begginer
Does the folder have to be named Resources, or can I name it something else?