[Solved] [A16] Injecting MapComponent into Existing Save?

Started by maarx1337, April 01, 2017, 06:24:42 PM

Previous topic - Next topic

maarx1337

I am trying to figure out the best way to inject a MapComponent if the mod is enabled and then a prior save game is loaded.

I found this thread, but the thread is old, I am not sure if it is still the best way to do it: https://ludeon.com/forums/index.php?topic=11187.msg111498

I am starting to get the impression that a better way is to use [StaticConstructorOnStartup] and LongEventHandler.QueueLongEvent(...) but I am having trouble determining what string value to pass for string textKey and/or levelToLoad.

I am finding a couple random examples using textKey "LibraryStartup" but this doesn't seem to be the correct value in my case.

I am having trouble identifying what other choices are available here / which I should use.

maarx1337

#1
I did it! Hooray!

Code is below.

The magic seems to be that the Constructor for the Component is called in all cases when a level is loaded (but not at the menu), even though for existing games, the Map doesn't actually gain the Component. So this is a solid starting point. And you cannot perform the function of "ensureComponentExists" from within the Constructor itself (my guess is some perfectly sane reasoning about why it is awful to nest constructors), but LongEventHandler.QueueLongEvent and/or static method (not sure which, or both) gives us whatever delay/context is necessary to land in the right place and be able to work our magic, even without specifying any significant textKey into QueueLongEvent.

public class MapComponent_OrderedHauling : MapComponent
{

public MapComponent_OrderedHauling(Map map) : base(map)
{
LongEventHandler.QueueLongEvent(ensureComponentExists, null, false, null);
}

public static void ensureComponentExists()
{
foreach (Map m in Find.Maps)
{
if (m.GetComponent<MapComponent_OrderedHauling>() == null)
{
m.components.Add(new MapComponent_OrderedHauling(m));
}
}
}

}