- Unity 2017 Game Optimization(Second Edition)
- Chris Dickinson
- 263字
- 2021-07-02 23:21:10
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.
- C#高級編程(第10版) C# 6 & .NET Core 1.0 (.NET開發經典名著)
- 深入理解Android(卷I)
- Java從入門到精通(第4版)
- Java開發入行真功夫
- 征服RIA
- 名師講壇:Java微服務架構實戰(SpringBoot+SpringCloud+Docker+RabbitMQ)
- Teaching with Google Classroom
- C語言程序設計
- Building Android UIs with Custom Views
- Extreme C
- Spring 5 Design Patterns
- C指針原理揭秘:基于底層實現機制
- 玩轉.NET Micro Framework移植:基于STM32F10x處理器
- Java高手是怎樣煉成的:原理、方法與實踐
- Elasticsearch Blueprints