UnluckDistanceDisabler.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using UnityEngine;
  2. using System.Collections;
  3. //Attach this to a prefab or gameobject that you would like to disable based on distance to another object. Like main camera or player.
  4. public class UnluckDistanceDisabler : MonoBehaviour {
  5. public int _distanceDisable = 1000;
  6. public Transform _distanceFrom;
  7. public bool _distanceFromMainCam;
  8. #if UNITY_4_5
  9. [Tooltip("The amount of time in seconds between checks")]
  10. #endif
  11. public float _disableCheckInterval = 10.0f;
  12. #if UNITY_4_5
  13. [Tooltip("The amount of time in seconds between checks")]
  14. #endif
  15. public float _enableCheckInterval = 1.0f;
  16. public bool _disableOnStart;
  17. public void Start()
  18. {
  19. if (_distanceFromMainCam){
  20. _distanceFrom = Camera.main.transform;
  21. }
  22. InvokeRepeating("CheckDisable", _disableCheckInterval + (Random.value * _disableCheckInterval), _disableCheckInterval);
  23. InvokeRepeating("CheckEnable", _enableCheckInterval + (Random.value * _enableCheckInterval), _enableCheckInterval);
  24. Invoke("DisableOnStart", 0.01f);
  25. }
  26. public void DisableOnStart(){
  27. if (_disableOnStart){
  28. gameObject.SetActive(false);
  29. }
  30. }
  31. public void CheckDisable(){
  32. if (gameObject.activeInHierarchy && (transform.position - _distanceFrom.position).sqrMagnitude > _distanceDisable * _distanceDisable){
  33. gameObject.SetActive(false);
  34. }
  35. }
  36. public void CheckEnable(){
  37. if (!gameObject.activeInHierarchy && (transform.position - _distanceFrom.position).sqrMagnitude < _distanceDisable * _distanceDisable){
  38. gameObject.SetActive(true);
  39. }
  40. }
  41. }