The host has prepared player-objects (spaceships) and manages the positioning and spawning of the objects before giving them to the players:
NetworkObject ship = [...]
[... set transform.position...]
ship.gameObject.SetActive(true);
ship.Spawn();
ship.ChangeOwnership(client);
Now, there are some player-specific UI-Elements like HUD-healthbars or HUD-sensors to be initialized, which means that the ship reference has to be set for each player UI (= Game instance). I tried several ways to do that and think that maybe OnGainedOwnership() would be the best try, so:
public override void OnGainedOwnership()
{
UIManager uiManager = GameObject.Find("UIManager").GetComponent<UIManager>();
Logger.Log(LogTag, "UIManager is: " + uiManager);
[...]
}
Now, this works perfectly fine with the host game instance.
But with the client game instance, GameObject.Find(…) just does not work and returns NULL. I tried with other Find-methods and finding other gameObjects and other timings (like in FixedUpdate()), but the method just returns NULL. Of course the UIManager gameobject is present which can be seen in the inspector.
Why does GameObject.Find(…) return NULL? What am i missing? Thanks a lot for your help in advance.
Try with FindObjectOfType(), and log that.
If it still doesn’t work, then it seems that the UIManager really does not exist for the clients or is turned off, so you should verify that.
I tried, but it still fails.
Here, an excerpt from the hierarchy view of the inspector shows that the UIManager is active and present:
Please don’t be confused with the names. I shortened the name above to make it simpler to read. The gameobject that calls the Find-method is the raptor(Clone) directly below that.
My code looks like this:
Results in Log:
I don’t really have an idea why this happens, but I would probably try doing some (in)sanity tests, like doing the same in update, just to see if at any point that UIManager can be found. Anything that you think will help you debug this issue.
I think i have figured it out. It looks like a timing problem. The host is acting too fast which leads to OnGainedOwnership() is called too early on client side. When OnGainedOwnership() is called, the MissionUIManager gameobject is somehow not yet active or started or whatever. The whole thing occurs directly after loading the scene, which means i will look for a way to make sure that all scene-placed objects are loaded client-side before the host starts to give the player objects to the clients.