Reputation: 484
I have in my assets a folder resources and inside an image pig.png, I want to create a sprite from code with this image, Here is my code:
var filePath = Application.dataPath + "/Resources/pig.png";
if (System.IO.File.Exists(filePath))
{
var bytes = System.IO.File.ReadAllBytes(filePath);
Texture2D tex = new Texture2D(1, 1);
tex.LoadImage(bytes);
Sprite sp = new Sprite();
sp = Sprite.Create(tex, new Rect(0, 0, 100, 100), new Vector2(0.5f, 0.5f),40);
}
The code runs when I click a button inside a gui, What's wrong?
Fixed code:
Texture2D tex = Resources.Load<Texture2D>("pig") as Texture2D;
Sprite sprite = new Sprite();
sprite = Sprite.Create(tex, new Rect(0, 0, 250, 150), new Vector2(0.5f, 0.5f));
GameObject newSprite = new GameObject();
newSprite.AddComponent<SpriteRenderer>();
SpriteRenderer SR = newSprite.GetComponent<SpriteRenderer>();
SR.sprite = sprite;
Upvotes: 0
Views: 586
Reputation: 125245
If your pig image is in the Assets/Resources
folder, then you have to load the image with Resources.Load
function not with File.ReadAllBytes
.
//Assign Sprite from Editor. (Where to display the loaded image sprite)
public Image displaySprite;
void loadImage()
{
//Load Image
Texture2D tex = Resources.Load("pig", typeof(Texture2D)) as Texture2D;
if (tex != null)
{
//Create new Sprite from the Loaded Sprite
Sprite sp = new Sprite();
sp = Sprite.Create(tex, new Rect(0, 0, 100, 100), new Vector2(0.5f, 0.5f), 40);
Debug.Log("Not Null");
//Show Image to screen
displaySprite.sprite = sp;
}
else
{
Debug.Log("Null");
}
}
Upvotes: 2