- Home /
Networking and UI Buttons
I have a Networked game where each player is essentially a floating camera, it's much like a Turn-based Strategy game.
Everything works fine up to unit selection.
When I have a selected unit there's a couple of options you can do, which are shown as buttons in the UI, Move, Shoot, Dodge, are some examples.
Unit selection is handled by a manager script that is part of the player's prefab. Which is instantiated(spawned) when they connect.
I have a problem when I have a unit selected and I click on the 'Move' button (or any of them really). How do I bind the 'onClick' function of the action to work on the player's selected model?
So say if there is a function in my player manager that enters "movementMode", called "EnterMovementMode()". Which has to be executed when the player clicked on the "Move" Button in the UI.
Seen in image bellow, The selected unit is highlighted by the green gear-like projector.
Should I make the GUI part of the player object and spawn it as a networkbehaviour object so it is pre-affixed to the action I want it to take?
I'm kinda stuck here
Thanks,
Answer by AurimasBlazulionis · Sep 10, 2016 at 05:13 PM
This is what I found on the internet:
thebutton.onClick.AddListener(delegate { YourFunction(anyParameters); }); }
You should add this to your manager and call it for each button.
Now how to get that button? Place a script which acts like a Button Cache. Inside it have something like public static ButtonCache instance;
. In start function do this:
instance = this;
Now you can write a variable for each button component and access each button like this:
ButtonCache.instance.whateverButton
Let me see if I'm understanding the solution correctly.
The player manager, when he joins the game either on Start or OnLocalPlayerStart, I get a reference to the button and set a delegate to it.
It would seem simple, but what I'm not getting is how to grab that reference. I'd like to avoid using something like GetObjectWithTag.
So something like having each button have a script that returns a reference to itself and then GetComponentInParent().GetComponent().onClick.AddListener... etc.
Would something like that work? Or am I totally off?
You could write a script which stores all the buttons. Place it in canvas. $$anonymous$$ake that script have a static variable which points to it. So in your manager, you can access that button by ButtonCache.instance.fireButton
. This seems like the cleanest solution.
I gotta be honest, it seems hacky. But by RNG it totally works!
Thanks a bunch! I can now move on with my project.
Also, in the answer, remove getcomponent as if you are writing the button cache, you can already store buttons as Button type.