Changing material runtime

Hi.
I need to change material runtime.
An actor (placed manually in the editor viewport) creates and spawns an instance of MyActor class (custom actor) in the world. MyActorScript is the script being attached to MyActor.
The code:

void Script01::OnStart()
{
auto act = New(SpawnParams(Guid::New(), MyActor::TypeInitializer));
MyActorScript* script = New < MyActorScript > () ;
script->SetParent(act);
Level::SpawnActor(act);
}

MyActorScript loads the model “Earth.flax” (imported from .fbx model) , loads the new material “JupiterMaterial.flax” and set this material to the model:

The code below:

AssetInfo info,infoMat;                                   // in MyActorScript.h
AssetReference<Model> model;                // in MyActorScript.h
AssetReference<Material> mat;               // in MyActorScript.h

void MyActorScript::OnStart() // in MyActorScript.cpp

{

StaticModel* smodel = New<StaticModel>();
String path("D:\\Flax1.3Projects/MyProject3/Content/Earth.flax");
if (Content::GetAssetInfo(path, info))
{
    model.Set(dynamic_cast<Model*>(LoadAsset(info.ID, Model::TypeInitializer)));
    smodel ->SetName(String("My Object"));
    smodel ->Model = model;
    smodel ->SetParent(GetActor());
    smodel ->SetStaticFlags(StaticFlags::None);
}

String pathMat("D:\\Flax1.3Projects/MyProject3/Content/JupiterMaterial.flax");
if (Content::GetAssetInfo(pathMat, infoMat)) 

{
mat.Set(dynamic_cast<Material*>(LoadAsset(infoMat.ID, Material::TypeInitializer)));
smodel ->SetMaterial(0, mat);
}
}

Compilation works,and I would expect the model Earth to show up with the new material JupiterMaterial.
When the project start the first time, there is no update of the material, and after the line
---------> smodel ->SetMaterial(0, mat); <---------
in the Output Log this message appears:

[ 01:22:42.746 ]: [Error] Check failed!
File: F:\FlaxEngine\Source\Engine\Level\Actors\ModelInstanceActor.cpp
Line: 21

Expression: entryIndex >= 0 && entryIndex < Entries.Count()

When the project starts again ,everything works,no errors, and the new material is used.
Is there a clean way to avoid this?
I have experimented with MaterialInstance and MaterialBase ,looking at the tutorials,but i have many crashes and no positive results.
Thank you!!!

I’ll fix this issue.

For now you could try using:

smodel->Model->WaitForLoaded();
smodel->SetMaterial(0, mat);

It works! Thank you very much :slightly_smiling_face: