user3822370
user3822370

Reputation: 647

Calling non-static methods in a static method

I am really stuck in some sort of static-hell that I've placed myself into. I have a server and client. The client asks the server for a list of lobbies. The client creates a graphical lists of buttons for each lobby. Each lobby button has a reference to Matchmaking's static method JoinLobby as this seemed the most simple way to hook up n amount of lobby buttons.

However after a lobby button calls JoinLobby (static) I wanted the Matchmaking class to toggle off some UI elements that are public but not static. I want to avoid making these elements static if possible, because I am using Unity and it breaks the workflow of using Unity's built-in drag-and-drop reference creator.

public class LobbyButton{
    public Button button;
    public Text name;
    public void JoinLobby(){
        Matchmaking.JoinLobby(name.text);
    }
}

public class Matchmaking{
   public LobbyList lobbyList; // UI list element

   public static void JoinLobby(string name){
        JoinServerLobby(name);
        lobbyList.Hide(); // can't do this, lobbyList not static
   }
}

I've run in to this situation a few times and always end up doing some work-around or total redo. But I am wondering if there is a more common way of "getting out" of this static call.

Upvotes: 0

Views: 707

Answers (2)

kamil-mrzyglod
kamil-mrzyglod

Reputation: 4998

In my opinion you have something wrong with your design.

Basically static means, that current member is a part of type, non an instance, thus mixing them to achieve some result, looks odd.

I think that you should inject Matchmaking to the LobbyButton button, store it as a field and reference to the non-static JoinLobby. I would leave static method to either utility tasks or generic functions, not related to the specific functionality.

Upvotes: 3

CodeCaster
CodeCaster

Reputation: 151588

Each lobby button has a reference to Matchmaking's static method JoinLobby as this seemed the most simple way to hook up n amount of lobby buttons.

Don't do that then.

In the form that has the "lobby buttons", keep a private variable with a reference to a Matchmaking instance. In the click events, refer to this variable.

You can also use the Tag property of buttons to give them an identifier, and hook them all up to the same click handler. There you check the Tag of the sender.

Upvotes: 2

Related Questions