using System.Collections.Generic; using UnityEngine; namespace GPUInstancer { public class GPUInstancerModificationCollider : MonoBehaviour { public GPUInstancerPrefabManager prefabManager; private List _enteredInstances; private Collider _collider; private void Awake() { _enteredInstances = new List(); _collider = GetComponent(); if(prefabManager == null) prefabManager = FindObjectOfType(); if (prefabManager != null) prefabManager.AddModificationCollider(this); else Debug.LogWarning("GPUInstancerModificationCollider does not have a GPUInstancerPrefabManager defined."); } private void Update() { if (prefabManager != null && prefabManager.isActiveAndEnabled) { Rigidbody rb; for (int i = 0; i < _enteredInstances.Count; i++) { GPUInstancerPrefab prefabInstance = _enteredInstances[i]; if (prefabInstance == null) { _enteredInstances.RemoveAt(i); i--; continue; } if (!IsInsideCollider(prefabInstance)) { rb = prefabInstance.GetComponent(); if (rb != null && !rb.IsSleeping()) continue; GPUInstancerAPI.EnableInstancingForInstance(prefabManager, prefabInstance); _enteredInstances.RemoveAt(i); i--; } else if (prefabInstance.state != PrefabInstancingState.Disabled) prefabManager.DisableIntancingForInstance(prefabInstance); } } } private void OnTriggerEnter(Collider collider) { if (prefabManager != null && prefabManager.isActiveAndEnabled && collider.gameObject) { GPUInstancerPrefab prefabInstance = collider.gameObject.GetComponent(); if(prefabInstance != null && prefabInstance.prefabPrototype.enableRuntimeModifications && prefabInstance.state != PrefabInstancingState.Disabled) { prefabManager.DisableIntancingForInstance(prefabInstance); _enteredInstances.Add(prefabInstance); } } } //private void OnTriggerExit(Collider collider) //{ // if (GPUInstancerPrefabManager.Instance != null && // collider.gameObject && // collider.gameObject.GetComponent() && // collider.gameObject.GetComponent().prefabPrototype.enableRuntimeModifications && // !gameObject.GetComponent().bounds.Intersects(collider.bounds)) // { // GPUInstancerPrefabManager.Instance.AddInstance(collider.gameObject.GetComponent()); // } //} public bool IsInsideCollider(GPUInstancerPrefab prefabInstance) { Collider instanceCollider = prefabInstance.GetComponent(); if (instanceCollider == null) return false; else return _collider.bounds.Intersects(instanceCollider.bounds); } public void AddEnteredInstance(GPUInstancerPrefab prefabInstance) { _enteredInstances.Add(prefabInstance); } public int GetEnteredInstanceCount() { return _enteredInstances.Count; } } }