problem with setting values of newly instantiated object
I worked 2 days to make me feel well with this script and now it's making problems. When I instantiate a new GameObject with this script attached to it, I somehow can't set any values in objects that need to be created in Start().
void Start () {
actions = new Actions(this);
connections = new Connections(this);
}
for example Actions has a boolean called "randomEnabled".
If i instantiate my GameObject and then try to change this property in the same method, it won't be changed.
How can I fix this?
Answer by Statement · Nov 01, 2015 at 11:48 PM
If i instantiate my GameObject and then try to change this property in the same method, it won't be changed.
So when you instantiate, Awake will be called on all components before you get the new instance back.
Start will be run before the next frame starts.
So, if you Instantiate(), then change some properties, a few moments later Start will be called, overwriting your changes.
Consider moving the code into Awake instead of Start.
I can't use Awake() because "this" doesn't work there. Allready tried that one.
I came up with my own possible solution to this, posting now.
hm, maybe you're right there. But if I move the code to Awake() the Constructor of Actions gives me a NullReferenceException:
public Actions(Lifeform parent) {
lfc = parent;
waypointPrefab = Resources.Load<GameObject>("Waypoint");
waypointList = lfc.planet.current.Find("Waypoints"); // <-- NRException
}
EDIT: found out, the problem here is current of lfc.planet
That's also a value that is set after instantiating the GameObject.
Answer by globalenemy · Nov 01, 2015 at 11:51 PM
Adding my own possible solution to this problem:
[HideInInspector] public bool rEnabled;
[HideInInspector] public bool iByContact;
[HideInInspector] public bool iEnabled;
void Start () {
actions = new Actions(this, rEnabled);
connections = new Connections(this, iByContact, iEnabled);
}
I created variables in the main class to store the values. And then added the values to the Constructor of the objects.
[HideInInspector] was just used to keep the Inspector window of the editor clean.