People who are just starting to mod using multiloader template often ask a question about how to register items, blocks, entities and other objects. I'll show you how.
First problem you will encounter if you instantiate your objects in the common project and then trying to register them in every modloader is that the game crashes. That is because Minecraft allows instantiating objects only during registration phase. To circumvent this, we need to use lazy initialization.
I'll show how to use a subtype of lazy initialization - memoization. For this we have Google's library available that provides that.
Suppose you make a class to hold all your objects of particular kind, for example items:
ModItems.java
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
// a map that holds item identifiers and item objects
public static final HashMap<String, Supplier>Item>> ITEM_MAP =new HashMap<>();
// memoize the item object
public static final com.google.common.base.Supplier<Item> TITANIUM_INGOT= Suppliers.memoize(() -> new Item(new Item.Properties()));
// then put the item into the map
static {
ITEM_MAP.put("titanium_ingot",TITANIUM_INGOT);
}
Then you just use the map to register the items in the modloader-specific projects.
Fabric - register your items in the ModInitializer:
FabricMod.java
public class FabricMod implements ModInitializer {
@Override
public void onInitialize() {
//MainClass is your class that holds the mod ID
ModItems.ITEM_MAP.forEach((s, itemSupplier) -> Registry.register(BuiltInRegistries.ITEM,ResourceLocation.fromNamespaceAndPath(MainClass.ID,s),itemSupplier.get()));
}
}
Neoforge - register your items in the deferred register:
NeoforgeMod.java
static final DeferredRegister<Item> ITEMS=DeferredRegister.createItems(MainClass.ID);
public class NeoforgeMod(IEventBus eventBus, ModContainer modContainer) throws IOException {
ModItems.ITEM_MAP.forEach(ITEMS::register);
ITEMS.register(eventBus);
}
And that's all you need to know how to register objects without using third-party libraries. Good luck!