I’m looking at making an RPG type game and have the character(s) appearance depend on what they have equipped. I’ve written code that can create JPGs based on the settings I feed into it. Problem is I’m not sure if I can swap in the new sprite data at runtime since I’ll be drawing the sprites from memory or disc and not from the resources folder in Unity. What I have so far is this:
void LateUpdate()
{
if (changeSprite)
changeSprite = false;
else
return;
Debug.Log ("Changing sprite");
try
{
foreach (var renderer in GetComponentsInChildren<SpriteRenderer>()) {
string spriteName = renderer.sprite.name;
Debug.Log (spriteName);
Texture2D myTexture = new Texture2D (85, 85);
Sprite newSprite;
string loadImagePath = "";
byte[] imageBytes = null;
Image loadImage = null;
switch (spriteName) {
case "Idle":
loadImage = Image.FromFile (@"c:\sprites\testperson\S\person_idle.jpg");
break;
case "Walk1":
loadImage = Image.FromFile (@"c:\sprites\testperson\S\person_walkA.jpg");
break;
case "Walk2":
loadImage = Image.FromFile (@"c:\sprites\testperson\S\person_walkB.jpg");
break;
}
var imageStream = new MemoryStream ();
loadImage.Save (imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
imageBytes = imageStream.ToArray ();
myTexture.LoadImage (imageBytes);
newSprite = Sprite.Create (myTexture, new Rect (0f, 0f, 85f, 85f), new Vector2 (0.5f, 0.5f));
newSprite.name = spriteName;
if (newSprite)
{
renderer.sprite = newSprite;
renderer.material.mainTexture = myTexture;
renderer.material.shader = Shader.Find("Sprites/Default");
}
}
}
catch (Exception ex) {
Debug.Log (ex.ToString ());
}
}
It still needs work since it only tries to change one of the animation sprites but even that doesn’t work. Is it not possible to do this because I’m not drawing from the resources folder or is there something I’m missing?
Thanks in advance for any help.