Does Unity load in memory textures that are target of public variables ? (iOS)

Hey !

I’m having performance issues on my iOS game and one of the questions I have to solve it is this :

I have some script that have public variables

public Texture tex;

Where I drop a texture in the Inspector view (texture are stored in the Assets/ folder)

When I press play I have a script that decide which texture to assign to the object material based on what’s happening in the game.

I was wondering if Unity load all the textures in the public variables when the game starts or just load the texture when they are applied on a Material at runtime.

renderer.sharedMaterial.mainTexture = tex;

If someone has an idea or a related article that I can read ?

Many thanks.

No, Unity does not load the texture until the texture is applied to a material that is on an object in the scene. It wouldn’t make sense to load everything that was referenced, because you may have 20 variants for your main character for instance, and video memory is already at a premium, especially on mobile devices. Another example is one game object that has 20 references for the sky cube map but changes the camera’s sky to only 1 of them based on the level loaded. The only memory used when you reference the texture above is to save information about the texture (such as the location, size, etc). Then when you assign it to a material, it is loaded into video memory.

If you are curious, create a cube in an empty scene with a script that references 10 very large textures, and set the OnMouseDown() to override the cube’s renderer material with a new texture each time. You can see the VRAM usage (among others) from the Stats window on the Game view, and it will change accordingly.

For your specific problem, if you are assigning the material in the editor to for instance the highest resolution one you have, then your game/app will start up, load all of the high res textures, then unload them and replace them with the proper resolution. So just make sure all of your textures are null as assigned to the game object in the editor (you might be able to add an if (!Application.IsEditor) type statement to the Awake method of the game object to dereference the mainTexture of your objects. That way you can still edit and run/test in the Unity editor, but the mainTexture will (hopefully, can’t say for sure) be null before you do the big swap over for the device-specific textures. Like:

void Awake() {
    if (!Application.isEditor)
        renderer.sharedMaterial.mainTexture = null;
}

This brings up another point. Make sure you are setting the sharedMaterial and not the material, because then every game object in your scene would get a new material that might cause a slowdown.