Skip to content

Instantly share code, notes, and snippets.

@gekidoslair
Created October 12, 2021 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gekidoslair/ee613dcafd015bdc3e00c99422f524e9 to your computer and use it in GitHub Desktop.
Save gekidoslair/ee613dcafd015bdc3e00c99422f524e9 to your computer and use it in GitHub Desktop.
Unity - Only One Can Survive
using UnityEngine;
namespace PixelWizards.GameSystem.Controllers
{
/// <summary>
/// Lets us include specific prefabs in multiple scenes and make sure we don't end up with duplicates in the end
/// sort of an inverse singleton pattern. Basically add this to a prefab, then add that prefab into any scene and
/// no matter what only one is ever active
/// </summary>
public class OnlyOneCanSurvive : MonoBehaviour
{
private void OnEnable()
{
// see if there are other contenders
var obj = GameObject.FindObjectsOfType<OnlyOneCanSurvive>();
if( obj.Length > 0)
{
for( var i = 0; i < obj.Length; i++)
{
// if it's not 'us', then check and see if we're the same
if( obj[i].gameObject != this.gameObject)
{
// if there's already an object with this name, then we nuke ourselves
if( obj[i].name == this.gameObject.name)
{
Destroy(this.gameObject);
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment