Skip to content

Instantly share code, notes, and snippets.

@theWill
Created April 23, 2019 19:03
Show Gist options
  • Save theWill/7847f9bf1cd956e3c8db87fcd1f4e1ce to your computer and use it in GitHub Desktop.
Save theWill/7847f9bf1cd956e3c8db87fcd1f4e1ce to your computer and use it in GitHub Desktop.
ForgeNetworking LAN discovery code by Faun Lily Studios
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 void Start()
{
acceptingInput = true;
}
public void now()
{
if (!acceptingInput)
return;
lock (inputLock)
{
acceptingInput = false;
numSearches = 0;
enableSonar();
StartCoroutine(actualSearch());
}
}
private void enableSonar(bool enabled = true)
{
showSonarPanel(enabled);
enableSonarIcon(enabled);
}
private void searchComplete()
{
Debug.Log("SearchComplete");
lanSearchComplete.Raise();
StartCoroutine(smallCooldownAfterSearch());
}
private IEnumerator smallCooldownAfterSearch()
{
yield return new WaitForSeconds(.5f);
acceptingInput = true;
enableSonar(false);
}
private IEnumerator actualSearch()
{
//base case
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 > 0)
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