An Opportunity To Improve Your Programming Skills

I’ve been busy working on the space sim for the past few weeks. At the end of this month the first early access release will be sent to STEAM. It won’t have any game play content. It will be a tool used to create game content. The idea is to provide players the exact tools I’m making that will be used to create the game. This space sim is going to be mod friendly from the ground up. Future updates will add more tools and an actual space sim that can be modified by the tools. As readers can see I’ve also posted about current events. I love the United States Constitution. I am not a fan of dictators and/or communists; both hate liberty and want to tear down freedom.

In this post I’ll show a way, one of many, to import a png image into a game at runtime without using Unity’s resource folders.

Here’s the code:

public Texture2D LoadPNG(string pathOfPNGtoLoadFromDisk)
{
byte[] pngArray = File.ReadAllBytes(fullFilePath);
Texture2D tempTexture = new Texture2D(256,256);
//you can set the resolution of the texture to whatever. Unity will scale the image accordingly. It’s best not to //create a texture resolution that is higher than the image resolution as that will result in pixilation.
tempTexture.LoadImage(pngArray);
return tempTexture;
}

Most likely you would then want to convert the texture into a sprite and assign that sprite as an image on a UI element or a 2d game object.

I’ve included a link to the Unity documentation that shows how to create a sprite from a texture2d.

Unity – Scripting API: Sprite.Create (unity3d.com)

Your mission, should you choose to accept it, is to modify the code I’ve provided to create a sprite from the tempTexture variable and change the method to return a sprite instead of a Texture2d.

You also need to include

using System.IO;

in the script because of the following line in the code:

byte[] pngArray = File.ReadAllBytes(fullFilePath);

File.ReadAllBytes(String) Method (System.IO) | Microsoft Docs

Good luck 🙂