Loading in textures dynamically without using Resources


My game currently needs to load in assets (like textures) dynamically, in script, without using the Unity Resources folder. I’m using C#.

This is what I’m using:

public static Texture2D LoadTexture(string filePath)
            var bytes = System.IO.File.ReadAllBytes(filePath);
            var tex = new Texture2D(2, 2, TextureFormat.DXT1, false);

            return tex;

And this is what I used to be doing:

var newTexture = Resources.Load<Texture2D>(fileName);

My problem is that they don’t seem to be doing the same thing. When testing, my sprites (using these textures) seemed half as wide when loading it without Resources. When I took at look at the textures in question and compared them, I realised that there were two fundamental differences:

  1. The format of the textures were different, but this is a caveat of the LoadImage() function (as stated in its documentation it reverts to a default format for JPG and PNG files). I’m not too worried about this.

2) The texel size for textures of size (6, 6) was different. Resources.Load texture had a texel size of (0.2, 0.2) while my LoadImage texture had a texel size of (0.1, 0.1). I’m guessing that this was the cause for the weird looking sprites.

So what I’m asking for is: What am I doing wrong? OR How do I fix this discrepancy?

Note: There are a few lines of code that I’ve edited out for sake of simplicity (I’m changing texture filter modes, names, etc).

If you need any further information I’d be happy to provide it.

Not sure what the issue there is, but you can try using WWW.LoadImageIntoTexture instead as it supports Unity textures a lot better. You can use it with the File:// protocol instead of the https:// protocol to get files from the disc.