Add ModuleInitializer attribute for C# scripting initialization code running on load

This commit is contained in:
Wojciech Figat
2022-10-12 17:00:40 +02:00
parent 09b35266f7
commit 77f8df02e5
2 changed files with 36 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
// Copyright (c) 2012-2022 Wojciech Figat. All rights reserved.
using System;
namespace FlaxEngine
{
/// <summary>
/// Indicates that a static class initializes the code module. All static, void and parameterless methods within the class will be invoked upon module loading.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class ModuleInitializerAttribute : Attribute
{
}
}

View File

@@ -947,6 +947,28 @@ void ManagedBinaryModule::OnLoaded(MAssembly* assembly)
InitType(mclass);
}
}
// Invoke module initializers
if (flaxEngine->Assembly->IsLoaded() && this != flaxEngine)
{
const MClass* attribute = flaxEngine->Assembly->GetClass("FlaxEngine.ModuleInitializerAttribute");
ASSERT_LOW_LAYER(attribute);
for (auto i = classes.Begin(); i.IsNotEnd(); ++i)
{
MClass* mclass = i->Value;
if (mclass->IsStatic() && !mclass->IsInterface() && mclass->HasAttribute(attribute))
{
const auto& methods = mclass->GetMethods();
for (const MMethod* method : methods)
{
if (method->GetParametersCount() == 0)
{
method->Invoke(nullptr, nullptr, nullptr);
}
}
}
}
}
#endif
}