private void Update() { for (int i = 0; i < _currentObjects.Count; i++) { keep(i, false); } if (_hasTarget) { var vector = _targetPosition - transform.position; for (int i = 0; i < Physics.RaycastNonAlloc(transform.position, vector, _hits, vector.magnitude); i++) { var hit = _hits[i]; var obj = hit.collider.gameObject; if (!hit.collider.isTrigger && (_target == null || !Util.InHiearchyOf(obj, _target))) { // Check if already fading int oldIndex = indexOf(_currentObjects, obj); if (oldIndex >= 0) { keep(oldIndex, true); continue; } // Check if was being removed oldIndex = indexOf(_oldObjects, obj); if (oldIndex >= 0) { _currentObjects.Add(_oldObjects[oldIndex]); keep(_currentObjects.Count - 1, true); _oldObjects.RemoveAt(oldIndex); continue; } // Create and add { FadedObject faded; faded.Fade = 0; faded.Object = obj; faded.KeepThisFrame = true; var gotRenderers = obj.GetComponentsInChildren <MeshRenderer>(); faded.Renderers = new FadedRenderer[gotRenderers.Length]; for (int k = 0; k < gotRenderers.Length; k++) { FadedRenderer renderer; renderer.Renderer = gotRenderers[k]; renderer.OriginalMaterial = Material.Instantiate(renderer.Renderer.material); renderer.NewMaterial = Material.Instantiate(renderer.Renderer.material); renderer.OriginalColor = renderer.OriginalMaterial.color; renderer.Renderer.material = renderer.NewMaterial; renderer.Renderer.gameObject.SendMessage("OnFade", SendMessageOptions.DontRequireReceiver); faded.Renderers[k] = renderer; } _currentObjects.Add(faded); } } } } for (int i = _currentObjects.Count - 1; i >= 0; i--) { if (!_currentObjects[i].KeepThisFrame) { _oldObjects.Add(_currentObjects[i]); _currentObjects.RemoveAt(i); } } for (int i = 0; i < _currentObjects.Count; i++) { var value = _currentObjects[i]; value.Fade = Mathf.Lerp(value.Fade, 1.0f, Time.deltaTime * Speed); fade(value.Renderers, value.Fade); _currentObjects[i] = value; } for (int i = _oldObjects.Count - 1; i >= 0; i--) { var value = _oldObjects[i]; value.Fade = Mathf.Lerp(value.Fade, 0, Time.deltaTime * Speed); fade(value.Renderers, value.Fade); if (value.Fade > float.Epsilon) { _oldObjects[i] = value; } else { foreach (var renderer in _oldObjects[i].Renderers) { renderer.Renderer.material = renderer.OriginalMaterial; renderer.Renderer.gameObject.SendMessage("OnUnfade", SendMessageOptions.DontRequireReceiver); } _oldObjects.RemoveAt(i); } } }