- Home /
Attach GUI element to newly spawned player as their GUI
Goal: Design and implement a multiplayer GUI. Specifically a hitpoints readout while also keeping the readout separate from other players in the same server.
I came across a few tutorials of the new 4.6 UI features and the typical method of adjusting the value of a slider or text is to:
1) Attach a script to an object
2) Write the GUI controls into the script (update hitpoints -> change slider value, for example)
3) Drag the GUI element from the hierarchy to the script in the inspector
The problem is the players with the health scripts attached are not spawned until they join a game. This means I would have to attach the slider to the script after the player spawns else I get object reference issues.
Suggestions? I am open to a better method as well. Thank you!
Hi. Same problem here with UI in unity 5.1. Did you find any way to solve it?
Answer by barjed · Nov 09, 2014 at 06:49 PM
Prepare a Prefab with all the connections and references inside. Leave an empty public property for the player object to connect in.
When a player spawns, simply instantiate the prefab using Instantiate()
, fill in the missing property and you're good to go :)
Thank you for your response!
To clarify:
I have a player prefab. If I leave the prefab in the project browser, select it, and try to drag my slider UI element to the inspector window onto the player's "health" script (it as a slot for it because the script has public Slider slider;
) it won't let me drop it there.
Alternatively, if I first drop the prefab into the world and then follow the steps above I -can- attach the UI element to the player's health script in the inspector. However, when I save this player as my new prefab the UI element is detached.
I do instantiate the prefab when the player spawns. GameObject myPlayerGO = (GameObject)PhotonNetwork.Instantiate("PlayerController", mySpawnSpot.transform.position, mySpawnSpot.transform.rotation, 0);
fill in the missing property and you're good to go :)
This is basically what I am asking how to do. How do I do this? :)
Ultimately all I want to do is have the player's health reflected in the UI element. Either a slider or text will do as I'm sure the method is similar.
Thanks again!