I want to instantiate a object who has a constructor. I read this two thread (How can I instantiate a object with a constructor? - Questions & Answers - Unity Discussions) ( Instantiate with constructor is it possible? ) but my case is diferent.
This is my code
newElementBody = Instantiate(
elementBody,
controller.GetWorldPositionLeft(),
Quaternion.identity,
transform
);
newElementBody.name = "Element Body";
public class ElementBody : MonoBehaviour
{
private ElementBody target;
ElementBody(ElementBody target)
{
this.target = target;
}
}
You can’t use constructors with monobehaviours as their life time doesn’t follow the same rules of non unity objects, given they only exist attached to game objects.
Instead of a constructor, just give it your own ‘Initialise’ method and call that after you get the return on the Instantiate.
But how can I reach the method? I can’t do newElementBody.Initiate(); becuse newElementBody is a gameObject and not a ElementBody. If I hange that the prefab wont work, and that needs to be a gameObject.
Please try and listen to what myself and others are saying.
Particularly this part in bold:
Firstly, Monobehaviours are not game objects. They are components on game objects. They live, breathe and die with game objects they are attached to. You can only create or remove them via the inspector, or with AddComponent or RemoveComponent, no exceptions. I already told you in the last thread that you can’t instantiate monobehaviours with constructors.
Secondly, you can serialise references to other components, including if said component is on the root game object of a prefab. If you Instantiate this reference, it will copy the game object this component is attached to and anything else with it. You also get the copy returned via the method.
You were already given a perfect example on how to achieve what you want in the previous thread.
1 Like
Ah, sorry for not reading it all. But it works now. Thx