# CreateWithShader can only be called from the main thread

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);
Debug.Log("------------Material--------------");
Debug.Log(materialName);
if (materialName == "VB") {
materialName = "material0";//work around
}

var newMtl = new Material(shader) { name = materialName };
mtlDict[materialName] = newMtl;
currentMaterial = newMtl;

continue;
}


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.

• 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? Jun 6 at 11:24