Reputation: 741
I'm trying to add a Quest-object to a Person. It succeeds for one and gives a nullreferenceexception for the other, what am I doing wrong here? P.S. The player and requestor are set in the Unity inspector.
public class GameCreator : MonoBehaviour {
private Quest quest;
public Player player;
public Requestor requestor;
void Start() {
quest = createQuest();
requestor.thisPerson.SetQuest(quest); //this is the problem
player.thisPerson.SetQuest(quest);
}
}
public class Player : MonoBehaviour {
public Person thisPerson;
void Start() {
thisPerson = new Person("Name");
}
}
public class Requestor: MonoBehaviour {
public Person thisPerson;
void Start() {
thisPerson = new Person("Name");
}
}
public class Person {
public Quest quest;
void SetQuest(Quest quest) {
this.quest = quest;
}
}
Any suggestions why this is going wrong?
Upvotes: 0
Views: 1411
Reputation: 13337
As Jordak said, your Start methods can run in any possible order, so you can't rely on Start of some component in the other. You have several ways to address this issue:
Upvotes: 1
Reputation: 4056
Move your variable initialization in to Awake()
, see the documentation for the following (paraphrased):
Awake is used to initialize any variables or game state before the game starts.... and use Start to pass any information back and forth.
The way your GameCreator.Start()
is written you are reliant on the arbitrary order in which Unity calls your scripts. GameCreator
could be the first object called, in which case none of your other scripts have initialized their values.
Other possible errors:
requestor
, I'm going to assume this was done in Unity's Inspector.Upvotes: 3