Skip to content

Instantly share code, notes, and snippets.

@theWill
Created May 28, 2019 18:21
Show Gist options
  • Save theWill/2e89719bb3f83b486730fa267dc19bed to your computer and use it in GitHub Desktop.
Save theWill/2e89719bb3f83b486730fa267dc19bed to your computer and use it in GitHub Desktop.
Forge Remastered - co-routines for managing the LAN search
using BeardedManStudios.Forge.Networking;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LANSearch : MonoBehaviour {
public Animator sonarPanelAnimator;
public Animator sonarIconAnimator;
private int numSearches;
public int maxSearches;
public float waitTime;
public GameEvent lanSearchComplete;
private readonly object inputLock = new object();
public bool acceptingInput;
public bool quicksearch;
public GameEvent hideConnecting;
public void Start()
{
acceptingInput = true;
quicksearch = false;
}
public void now()
{
if (!acceptingInput)
return;
lock (inputLock)
{
hideConnecting.Raise();
acceptingInput = false;
numSearches = 0;
enableSonar();
StartCoroutine(actualSearch());
}
}
public void quicksearchNow()
{
quicksearch = true;
now();
}
private void enableSonar(bool enabled = true)
{
showSonarPanel(enabled);
enableSonarIcon(enabled);
}
private void searchComplete()
{
//Debug.Log("SearchComplete");
if(!quicksearch || NetWorker.LocalEndpoints.Count > 1)
lanSearchComplete.Raise();
StartCoroutine(smallCooldownAfterSearch());
}
private IEnumerator smallCooldownAfterSearch()
{
yield return new WaitForSeconds(.5f);
acceptingInput = true;
enableSonar(false);
quicksearch = false;
}
private IEnumerator actualSearch()
{
if (numSearches >= maxSearches)
{
searchComplete();
yield break;
}
try
{
NetWorker.RefreshLocalUdpListings(GameManager.PORT_NUM);
} catch (System.Exception e)
{
Debug.Log("some failure during lan search: " + e);
}
numSearches++;
yield return new WaitForSeconds(waitTime);
checkSearchResults();
}
private void checkSearchResults()
{
if (NetWorker.LocalEndpoints.Count > 1)
searchComplete();
else
StartCoroutine(actualSearch()); //rereun the search
}
private void showSonarPanel(bool isShow = true)
{
sonarPanelAnimator.SetBool("showMenu", isShow);
}
public void enableSonarIcon(bool isAnimate = true)
{
sonarIconAnimator.SetBool("Animate", isAnimate);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment