官术网_书友最值得收藏!

Disabling objects by distance

In other situations, we may want components or GameObjects to be disabled after they are far enough away from the player such that they may be barely visible, but too far away to matter. A good candidate for this type of activity is roaming Non-Player Character creatures: we want to see them at a distance, but where we don't need them to process anything, and therefore they can sit idle until we get closer.

The following code is a simple coroutine that periodically checks the total distance from a given target object and disables itself if it strays too far away from it:

[SerializeField] GameObject _target;
[SerializeField] float _maxDistance;
[SerializeField] int _coroutineFrameDelay;

void Start() {
StartCoroutine(DisableAtADistance());
}

IEnumerator DisableAtADistance() {
while(true) {
float distSqrd = (transform.position - _target.transform.position).sqrMagnitude;
if (distSqrd < _maxDistance * _maxDistance) {
enabled = true;
} else {
enabled = false;
}

for (int i = 0; i < _coroutineFrameDelay; ++i) {
yield return new WaitForEndOfFrame();
}
}
}

We should assign the player's character object (or whatever object we want it to compare with) to the _target field in the Inspector window, define the maximum distance in _maxDistance, and modify the frequency with which the coroutine is invoked using the _coroutineFrameDelay field. Anytime the object goes further than _maxDistance distance away from the object assigned to _target, it will be disabled. It will be re-enabled if it returns within that distance.

A subtle performance-enhancing feature of this implementation is comparing against distance-squared instead of the raw distance. This leads us conveniently to our next section.

主站蜘蛛池模板: 石泉县| 乌拉特前旗| 祁东县| 游戏| 汾阳市| 牡丹江市| 陈巴尔虎旗| 会宁县| 建始县| 佛学| 柞水县| 简阳市| 东乌珠穆沁旗| 海原县| 诸暨市| 炉霍县| 廊坊市| 凌云县| 蒲城县| 敖汉旗| 许昌县| 东乡| 遂平县| 喜德县| 青河县| 东光县| 荆州市| 蕲春县| 团风县| 安庆市| 什邡市| 阆中市| 琼海市| 肇庆市| 白玉县| 洞口县| 繁昌县| 北川| 句容市| 武宁县| 林西县|