#(noob question) Singleton on a per local player basis
1 messages · Page 1 of 1 (latest)
NetworkClient.localPlayer.GetComponent<ScriptName>().
Is a shortcut
Personally i have one main script that gets set a reference to local player when they spawn in, and all other scripts use that one scripts reference.
edit
Player script:
public SceneScript sceneScript;
public override void OnStartLocalPlayer()
{
sceneScript = GameObject.Find(“SceneScript”).GetComponent<SceneScript>();
sceneScript.playerScript = this;
}
scene script: // a non networked script in the scene
public PlayerScript playerScript;
Now all my other scripts can use sceneScript.playerScript for local player access.
You can make the scene script a singleton, or a static variable etc
@formal parcel
ahj okay so kind of like I have done here already?
I created a singleton gamemanager where when the player stats it assignes its playerstats / inventory and have used the GM to access the other scripts
@radiant pelican
💪 yeah go for it
Perfect thanks!
I'd caution against this type of centralization. A GM singleton is fine for global game state, but leave instance-specific stuff in components on the player object, e.g. player stats, health, inventory, etc..
So would you say
Networkclient.localplayer is better to use?
for cross ref between components on the player, expose fields on the components where you can assign refs to other components in the inspector and assign them at design time or through RequireComponent + OnValidate. This assumes you're not making a massive single Player component, but instead having a bunch of narrow scope components on the player object.
Amazing thank you!!
Apologies, another question.
If I have multiple scripts with a reference to my playerStats script component. is that not inefficient? essencially having multiple variables of the same thing?
They're just ref pointers in different scopes...it's fine.