I'm currently using the following general pattern for most of my configurable components (i.e. MonoBehaviour
s):
public class MyComponent : MonoBehaviour
{
// Configurable fields
[SerializeField]
private bool someParameter;
[SerializeField]
private int anotherParameter;
// Fake constructor to act as a replacement for GameObject.AddComponent
// with additional parameters.
public static MyComponent AddTo(GameObject gameObject, bool someParameter, int anotherParameter)
{
var myComponent = gameObject.AddComponent<MyComponent>();
myComponent.someParameter = someParameter;
myComponent.anotherParameter = anotherParameter;
return myComponent;
}
// Public properties and other methods
// ...
}
This works around the lack of constructors for MonoBehaviour
s but still encapsulates the parameters in such a way, that they can only be set at the time the object is created, or through the Inspector (which is effectively the same thing once the game is built).
Unfortunately, this approach doesn't help once I want to use my component inside a prefab. When I instantiate the prefab, the component has already been created, and I can no longer touch those parameters. And as far as my google-fu can tell, there's no way to pass parameters into prefab instantiation (much like there isn't a way to pass a parameter into AddComponent
). It seems like everyone just instantiates their prefabs and then fiddles with some public properties to configure them.
So the question is, is there any way to set things up, such that I can configure some fields on my prefabs, but without exposing them publicly and breaking encapsulation?
(I realise that I could add a similar static "factory" method which instantiates a specific prefab and then configures the component inside that prefab, but a) this means adding one such method for each prefab and b) it breaks down once I want to configure multiple components within the same prefab.)