79 lines
2.3 KiB
C#
79 lines
2.3 KiB
C#
using UnityEngine;
|
|
using System.Collections;
|
|
|
|
//Attach this to a prefab or gameobject that you would like to disable based on distance to another object. Like main camera or player.
|
|
|
|
public class UnluckDistanceDisabler : MonoBehaviour {
|
|
public int _distanceDisable = 1000;
|
|
public Transform _distanceFrom;
|
|
public bool _distanceFromMainCam;
|
|
#if UNITY_4_5
|
|
[Tooltip("The amount of time in seconds between checks")]
|
|
#endif
|
|
public float _disableCheckInterval = 10.0f;
|
|
#if UNITY_4_5
|
|
[Tooltip("The amount of time in seconds between checks")]
|
|
#endif
|
|
public float _enableCheckInterval = 1.0f;
|
|
public bool _disableOnStart;
|
|
public bool _useDistanceFade = false;
|
|
public float _fadeRange = 5f;
|
|
int m_fadeDistanceID = Shader.PropertyToID("_FarFadeDistance");
|
|
private int m_invFadeDistanceRangeID = Shader.PropertyToID("_InverseFarFadeRange");
|
|
Material[] m_materials;
|
|
|
|
void SetupMaterials()
|
|
{
|
|
int matNum = 0;
|
|
var meshes = transform.GetComponentsInChildren<Renderer>();
|
|
|
|
for (int i = 0; i < meshes.Length; i++)
|
|
{
|
|
matNum += meshes[i].materials.Length;
|
|
}
|
|
|
|
m_materials = new Material[matNum];
|
|
int cnt = 0;
|
|
for (int i = 0; i < m_materials.Length; i++)
|
|
{
|
|
for (int j=0; j<meshes[i].materials.Length; j++)
|
|
m_materials[cnt++] = meshes[i].materials[j];
|
|
}
|
|
|
|
float invDist = 1f / _fadeRange;
|
|
foreach (var m in m_materials)
|
|
{
|
|
m.SetFloat(m_fadeDistanceID, _distanceDisable);
|
|
m.SetFloat(m_invFadeDistanceRangeID, invDist);
|
|
}
|
|
}
|
|
public void Start()
|
|
{
|
|
if (_distanceFromMainCam){
|
|
_distanceFrom = Camera.main.transform;
|
|
}
|
|
InvokeRepeating("CheckDisable", _disableCheckInterval + (Random.value * _disableCheckInterval), _disableCheckInterval);
|
|
InvokeRepeating("CheckEnable", _enableCheckInterval + (Random.value * _enableCheckInterval), _enableCheckInterval);
|
|
Invoke("DisableOnStart", 0.01f);
|
|
if (_useDistanceFade)
|
|
SetupMaterials();
|
|
}
|
|
|
|
public void DisableOnStart(){
|
|
if (_disableOnStart){
|
|
gameObject.SetActive(false);
|
|
}
|
|
}
|
|
|
|
public void CheckDisable(){
|
|
if (gameObject.activeInHierarchy && (transform.position - _distanceFrom.position).sqrMagnitude > _distanceDisable * _distanceDisable){
|
|
gameObject.SetActive(false);
|
|
}
|
|
}
|
|
|
|
public void CheckEnable(){
|
|
if (!gameObject.activeInHierarchy && (transform.position - _distanceFrom.position).sqrMagnitude < _distanceDisable * _distanceDisable){
|
|
gameObject.SetActive(true);
|
|
}
|
|
}
|
|
} |