Reputation: 57
I've got a problem during import a .png file to my project in code.
This is my .png file before importing:
After this code:
var pngImage = LoadPNG(pngPath);
string pngPath2 = Application.persistentDataPath + "/images/testImage.png";
var meshRenderer = GameObject.Find("SimInput").GetComponent<MeshRenderer>();
meshRenderer.material.mainTexture = pngImage;
public static Texture2D LoadPNG(string filePath)
{
Texture2D tex = null;
byte[] fileData;
if (File.Exists(filePath))
{
fileData = File.ReadAllBytes(filePath);
tex = new Texture2D(2, 2);
tex.LoadImage(fileData);
}
return tex;
}
I get the result as shown below:
Where am I doing a mistake?
I have been trying save this file again as a .png but the result was the same as on the first picture. Is there any property to change in Unity?
Thank you in advance.
Upvotes: 1
Views: 782
Reputation: 125275
This is a transparency issue. You are using the standard material which has it's "Rendering Mode" to set "Opaque". You have to set that to "Fade" or "Transparent". In this case "Fade", should work better. After this, you can then control the Metallic and Smoothness sliders to make it darker or lighter. You can also use another shader such as Sprites ---> Default, UI ---> Default or Unlit ---> Transparent and they should work without having to set anything else.
While this will solve your issue, if all you need to do is display the loaded Texture, use the RawImage
component. This is is the appropriate way to display Texture2D
. To create it, go to GameObject ---> UI ---> RawImage then use the simple code below to display it on the RawImage.
//Set a RawImage in the Inspector
public RawImage rawImage;
void Start()
{
Texture2D pngImage = LoadPNG(pngPath);
rawImage.texture = pngImage;
}
Upvotes: 2