Created
October 12, 2021 02:19
-
-
Save gekidoslair/ee613dcafd015bdc3e00c99422f524e9 to your computer and use it in GitHub Desktop.
Unity - Only One Can Survive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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