I’m encountering a recurring design problem in my Unity coding, and I’d like to see if others have found a satisfactory solution. To understand the problem, let’s start by comparing the traditional c# class constructor with ‘Object.Instantiate’:
-
C# class constructors can accept
generic input parameters which can be
customized by the developer. -
Object.Instantiate, on the other hand, allows only a fixed set of
input parameters. These parameters
are used to define the transform for
the instantiated object, we can’t
customize beyond that.
So, we can’t pass data of our choosing to the object created by Object.Instantiate in the same way that we could pass to a class constructor. Which leads to the question, how do you pass such data?
I’ve been using a few patterns to pass this data. My current solution is to Object.Instantiate the object, then pass in needed data after Instantiation:
// instantiate our prefab
GameObject instantiatedObject = Object.Instantiate(prefabResource, Vector3.zero, Quaternion.identity) as GameObject;
// get the MonoBehavior that's attached to this object
SomeMonoBehavior mono = instantiatedObject.GetComponent(typeof(SomeMonoBehavior)) as SomeMonoBehavior;
mono.field1 = new foobar();
mono.field2 = new foobaz();
...
this works, but It doesn’t feel elegant, and I end up creating a lot of ‘boilerplate’ code to handle what would typically be handled by a class constructor.
I’m not blocked on this, but I feel like there’s a better solution for this that I’m missing. Thanks!