Invoke & Waitforseconds not working

Hi,

I was just busy creating a systeem in which when I press a button it joins a random game and when there is no game available it creates a new one. However there is a problem when a 0 servers are available a new server is created and it adds 1 to AvailableSevers how ever this also causes it to read the part of availableservers > 0 because we just added one. I wanted to solve this by having a delay so that this function (available server > 0) is not called for me but is called for the next person (client) that wants to join a lobby. I tried doing this with the invoke and the waitforseconds but both don’t seem to work when I try to call them. Does anyone has a solution to this?

using UnityEngine;
using System.Collections;

public class MainMenu : MonoBehaviour
{
    public int curMenu = 0;

    public float dif = 1;
    private string gameName = "Server";

    //You have to change this!
    public string uniqueGame = "TheWestGamesNL";

   
    public float TimePassed = 4;
   
    public int AvailableServers;

    void Start()
    {

    }

    void Update()
    {
        dif = (Screen.width / 12.8f) / 100;
       
    }

    void OnGUI()
    {
       
        if (curMenu == 1)
        {
            GUI.Box(new Rect(20 * dif, 20 * dif, 200 * dif, 200 * dif), "");
            GUILayout.BeginArea(new Rect(25 * dif, 25 * dif, 190 * dif, 190 * dif));
            gameName = GUILayout.TextField(gameName);
            
            if (GUILayout.Button("Join game"))
            {
                if (AvailableServers == 0)
                {
                    Network.InitializeSecurity();
                    Network.InitializeServer(17, 25001, /*!Network.HavePublicAddress()*/ true);
                    MasterServer.RegisterHost(uniqueGame, gameName);
                    Debug.Log("available servers" + AvailableServers);
                    Invoke("ADDAvailableServers", 5);
                }
                if (AvailableServers > 0)
                {
                    Network.Connect("127.0.0.1", 25001);
                }
            }
        }
       
    }

    void ADDAvailableServers()
    {
        AvailableServers++;
        Debug.Log("Servers = " + AvailableServers);
    }

}

Why not an else if? That way if the first if is true, the else if never runs, if the first is false, it will run the else if instead.

You could also just do an else if you only have two options. It’s either going to == 0 or it’s going to be > 0, for example.

1 Like

Thanks dude, this worked perfectly! Don’t even know why I didn’t do it like this in the first place XD