I’m trying to create a gameobject with some setup parameters. For a normal c# class you would set them as the arguments in the constructor. But that can’t be done with the instatiate method for a game object. So I’m trying somthing like this:
public void CreateSettlement(int x, int y)
{
Settlement newSettlement = Instantiate(settlement);
newSettlement.SetPosition(x, y);
}
The problem (I think) is that the game component with the SetPosition method isn’t created in the Instantiate method fast enough, so I get a NullRef error when newSettlement.SetPosition(x, y);
is called.
Any ideas on how to fix this? It seems like a somewhat typical problem.
For starters, ensure your settlement variable is set.
Next I would check to see if you get anything out of the instantiate by assigning it to a more generic gameobject type. I usually assign to gameobjects myself then get the component I want from that.
If SetPosition
is referencing a component on the GameObject you’re instantiating, have the GameObject get the component in Awake
instead of Start
.
Generally, it’s a good idea to have GameObjects initialize all of their own components in Awake
, and reference components from other GameObjects in Start
, because Awake
runs before Start
. This way, you avoid the conflict of referencing components from other GameObjects before they’ve been assigned.
I hope Unity adds this somewhere in their documentation at some point, because it’s a common use-case, and it’s pretty misleading for new users when they create new MonoBehaviour scripts for the first time and are told to initialize everything in Start
, which inevitably leads to this issue.