Shamshirsaz.Navid
Shamshirsaz.Navid

Reputation: 2362

unity load sprit to gameobject from asset folder

I am new in Unity. i have a simple sprite in this address:

Assets <- (Folder)
|
 - Block <- (Block is a PNG file that dragged to unity project widget)

I want to add my "Block" sprite dinamically to my "Scene" or inside my "Main Camera" game object. I used this code to load block as Sprite:

Sprite block = Resources.Load<Sprite>( "Block" );
GameObject obj = new GameObject ("B1");
SpriteRenderer renderer = obj.AddComponent<SpriteRenderer> ();
obj.GetComponent<SpriteRenderer> ().sprite = block;
obj.GetComponent<SpriteRenderer> ().flipX = true;

I can see "B1" game object created in my scene and have no error in my console, but i cannot see the sprite on my scene.

enter image description here

Note: Unity: 5.6.7

Upvotes: 1

Views: 2567

Answers (1)

derHugo
derHugo

Reputation: 90629

It doesn't work for you because it would need to be placed inside a folder called Resources like Assets/Resources/Block.png


However: Don't use Resources at all!

Rather simply leave your file as it is and drag it into the Sprite field in the Inspector. If you really need to do it on runtime then make sure the component executing your code has according field like e.g.

// Drag the sprite from the Assets here via the Inspector
[SerializeField] private Sprite block;

private void YourMethod()
{
    var renderer = new GameObject ("B1").AddComponent<SpriteRenderer>();
    renderer.sprite = block;
    renderer.flipX = true;
}

Also if you are new to Unity you shouldn't start with a legacy version. Use either the latest stable version 2019.3.4f1 or go for the Long Term Supported 2018.4 LTS (though there soon will be the new LTS version 2019.4)

Upvotes: 3

Related Questions