Texturing a mesh created at runtime

I’m trying to dynamically apply a texture to a dynamically created mesh at runtime. In my script, which is a Billboarding script I use to have a simple quad always face the camera, the mesh is created and the texture applied in the Start() method. I’ve then drag dropped this script onto a GameObject in the scene.

This works fine in the Unity editor, but unfortunately on iOS and Android all I get is the pink mesh/billboard, which (to my understanding) is usually a symptom of a shader not having loaded or not being supported by the hardware.

I use the following code in the Start() method of my script (The GameObject the script is attached to also has a Character Controller script and some A* pathfinding scripts added to it).

gameObject.AddComponent("MeshFilter");
gameObject.AddComponent("MeshRenderer");
MeshFilter filter = GetComponent<MeshFilter>();
Mesh mesh = filter.mesh;
Renderer renderer = GetComponent<MeshRenderer>().renderer;
		
mesh.Clear();
mesh.vertices = vertices;
mesh.uv = uvs;
mesh.triangles = triangles;
mesh.RecalculateNormals();
		
renderer.material.mainTexture = Resources.Load("tank_icon") as Texture;
var shader = Shader.Find ("Particles/Alpha Blended");
gameObject.renderer.material.shader = shader;

Where tank_icon is really tank_icon.png, which is a 32bit RGBA .png and is located in the Assets/Resources folder.

Now, the weird part is that, let’s say I have a default plane GameObject added to the scene and I drag onto it that very same tank_icon.png and apply the “Particles/Alpha Blended” shader to it, then both the default plane and my billboarded quad (which was originally pink), renders correctly in both the Editor and Devices.

As soon as I remove the tank_icon material from the the Default plane GameObject, then my Billboarding GameObject is pink again (on device)

Could someone please share some insight as to what is going on and what I have to get this to work on the devices.

Thanks.

I apologise if this thread appears twice on the site but my previous attempt at this question got stuck in moderation and didn’t appear in my post history.

Unity only pulls in things that you reference. If you don’t reference a certain material or texture or script, Unity does not include it in the build. An attempt to dynamically load a shader using a string does not count as a reference. So if something in your build pulls in this shader, then the Shader.Find() will find it. If you don’t reference it anywhere, then it is not pulled in, and the Shader.Find() will fail.

You could create a material with this shader and assign it to the component through drag and drop in the editor…then assign the material instead of just the shader. My guess is that you could also dynamically load the material from Resources.