Adam's Lair Forum
https://forum.adamslair.net:80/

Load a sprite from file during runtime
https://forum.adamslair.net:80/viewtopic.php?f=4&t=1232
Page 1 of 1

Author:  tufduck [ 2018/06/06, 15:29 ]
Post subject:  Load a sprite from file during runtime

When I instantiate a prefab I wish to populate its SpriteRenderer component with a sprite from a png-file, not from a resource. I want to be able to write something like this:

Code:
public void PlayCardFromHand()
{
  GameObject card= CardPrefab.Res.Instantiate(transform.Pos, transform.Angle);
  card.GetComponent<SpriteRenderer>().Sprite = Load(@"\path\to\cardimage.png");
}

Is something like this possible?

I'm adapting a card game to Duality, and have over 1000 card images, so having all the cards as resources is not a viable solution.

Author:  SirePi [ 2018/06/06, 19:45 ]
Post subject:  Re: Load a sprite from file during runtime

Of course it's possible :D

there you go

Code:
using (Stream s = FileOp.Open(@"Y:\our\Path\Here.png", FileAccessMode.Read))
{
  IImageCodec codec = ImageCodec.GetRead(ImageCodec.FormatPng);
  PixelData pdata = codec.Read(s);
  Pixmap pmap = new Pixmap(pdata);
  Texture tex = new Texture(pmap /* extra parameters */);
  Material mat = new Material(DrawTechnique.Mask, ColorRgba.White, tex);
}


Please keep in mind that you can only load Textures while in the main thread loop of the game, otherwise you'll get a memory access exception. No shenaningans in the InitPlugin or separate threads.

EDIT: with this I mean that only the
Code:
Texture tex = new Texture(pmap /* extra parameters */);

line (and possibly the Material.. forgot) has to be performed in the main thread, due to OpenGL having to load the texture data in memory; the actual reading of the stream (the expensive part of the process), up to the instantiation of the Pixmap can very well be done in a separate thread.

Good luck :mrgreen:

Author:  tufduck [ 2018/06/07, 11:53 ]
Post subject:  Re: Load a sprite from file during runtime

Whoa, thank you sir! I've tried it and it works perfect. :1+:

Page 1 of 1 All times are UTC + 1 hour [ DST ]
Powered by phpBB® Forum Software © phpBB Group
http://www.phpbb.com/