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

Disabling objects by distance

In other situations, we may want Components or GameObjects to be disabled after they are enough far 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 AI creatures that we want to see at a distance, but where we don't need it to process anything, and it 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. Any time 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.

主站蜘蛛池模板: 翁牛特旗| 嘉荫县| 无锡市| 公主岭市| 嘉兴市| 涞水县| 平罗县| 武清区| 彩票| 保山市| 英山县| 锡林浩特市| 三原县| 廉江市| 浦江县| 丽江市| 余江县| 惠水县| 英山县| 内江市| 大安市| 潜江市| 丘北县| 依兰县| 三门峡市| 乌兰浩特市| 舞阳县| 祁阳县| 轮台县| 康保县| 手游| 郑州市| 全椒县| 峨山| 稷山县| 商河县| 湘潭市| 鄂州市| 阜新市| 洛阳市| 临湘市|