To add a component and initialize it with arguments, you can use the
GameObject.AddComponent<TComponent, T…> extension methods found in the Sisus.Init namespace.
These work very much like the built-in GameObject.AddComponent<T> methods, except you also specify the types of the Init arguments alongside the type of the added component as the generic argument of the method, and then pass in the Init arguments when calling the method.
using Sisus.Init; using UnityEngine; public static class GameManager { public static IInputManager InputManager { get; } = new InputManager(); public static Player CreatePlayer() { var gameObject = new GameObject("Player"); return gameObject.AddComponent<Player, IInputManager, Camera>(InputManager, Camera.main); } }
There are also alternative extension methods that can be used, which don’t return a value, but instead assign the created component to one of the method’s arguments that has the out modifier.
A benefit with these overloads is that you can generally use them without having to explicitly specify the generic arguments, as the compiler can infer them from the parameter types.
public static Player CreatePlayer() { var gameObject = new GameObject("Player"); gameObject.AddComponent(out Player player, InputManager, Camera.main); return player; }
You can also use new GameObject<TComponent…> to build a new GameObject, attach components to it and initialize those components with arguments, all in a single line of code.
using Sisus.Init; using UnityEngine; public static class GameManager { public static IInputManager InputManager { get; } = new InputManager(); public static Player CreatePlayer() { return new GameObject<Player>("Player").Init(InputManager, Camera.main); } }
If you want to instantiate your component by cloning a Prefab, instead of creating everything from scratch in code, you can do this, and initialize the created component with arguments, using the Object.Instantiate<TObject, T…> extension methods.
using Sisus.Init; using UnityEngine; public static class GameManager { public static IInputManager InputManager { get; } = new InputManager(); public static Player CreatePlayer(Player prefab) { return prefab.Instantiate(InputManager, Camera.main); } }