Note: I encounter a strange problem. I know that as the title suggests I have to create shader/material in main thread but the same code is working with other data without using the main thread.

I working to make runtime Obj Importer async. For this reason all the things are working fine and my code almost become async but its is very slow (which is a seperate question). Now, I stuck into a strange issue that when I get new material name string other than "materail0" then, i get an exception :

UnityException: CreateWithShader can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.

Here is the code which is inside Task.run:

if (splitLine[0] == "newmtl")
                string materialName = processedLine.Substring(7);
                if (materialName == "VB") { 
                    materialName = "material0";//work around
                var newMtl = new Material(shader) { name = materialName };
                mtlDict[materialName] = newMtl;
                currentMaterial = newMtl;


Now if the material name is == to "materail0" then all things work fine and there is no exception as I get another name of material like "VB" I get an exception.

  • \$\begingroup\$ This material code looks like stuff you want to defer to the main thread after the rest of the loading is completed. Can you show us how you've attempted to do that? \$\endgroup\$
    – DMGregory
    Jun 6 at 11:24


You must log in to answer this question.

Browse other questions tagged .