In unity multiplayer the player prefab spawns after the scene loads, what is the best way to declare scripts that are needed and avoid the NullReferenceException error?
Asked
Active
Viewed 356 times
2 Answers
0
I'm not that familiar with multiplayer myself, but I believe this could be done through GameObject.Find("") and GetComponent. I also stumbled across FindObjectOfType. I'm not sure if that's what you're looking for, but it doesn't hurt to post it. Good luck.

Mothil
- 166
- 5
0
Instead of letting a script look for when the prefabs have spawned why not letting the prefabs tell the script it has spawned?
It's really hard to give any kind of example when the use-case is not specified.
Really basic example (and since you're going to use it for networking you might have to redo this a lot so you don't trust the client too much):
class ScriptA : Monobehaviour () {
List<GameObject> prefabs;
public void AddPrefab (GameObject Prefab) {
prefabs.Add (Prefab)
}
}
class Prefab : Monobehaviour () {
void Start () {
FindObjectOfType(ScriptA).AddPrefab(gameObject);
}
}
It's not the best example but the point is, you might need to rethink the architecture

Indyz
- 321
- 3
- 7
-
I can't really change the way Unity 5 spawns in the player for multiplayer (a. with my level of knowledge or b.without a custom script. The player is the prefab, An example is that the player interacts with a coin that gives the player ten points, for instance the score system would be on the player and the coin would be already in the scene. When the level loads you would get a null exception error on the coin because it cannot find the score system it is trying to change. – Alan-Dean Simonds Aug 07 '16 at 07:49
-
That still sounds like an architectual issue, why does the coin have to access the score system when it's just supposed to change the individual score for players just when interacted with. The way i would go about it is that when a player interacts with the coin it invokes a method GiveMePoints() that returns the value of the coin and then the player adds that to it's score. – Indyz Aug 07 '16 at 12:45