using UnityEngine; using System.Collections; using UnityEngine.UI; namespace Nxr.Internal { public class NxrUICanvas : MonoBehaviour { protected BoxCollider canvasBoxCollider; protected Rigidbody canvasRigidBody; private void OnEnable() { SetupCanvas(); } void SetupCanvas() { var canvas = GetComponent(); if (!canvas || canvas.renderMode != RenderMode.WorldSpace) { return; } var canvasRectTransform = canvas.GetComponent(); var canvasSize = canvasRectTransform.sizeDelta; var defaultRaycaster = canvas.gameObject.GetComponent(); var customRaycaster = canvas.gameObject.GetComponent(); if (!customRaycaster) { customRaycaster = canvas.gameObject.AddComponent(); } if (defaultRaycaster && defaultRaycaster.enabled) { customRaycaster.ignoreReversedGraphics = defaultRaycaster.ignoreReversedGraphics; customRaycaster.blockingObjects = defaultRaycaster.blockingObjects; defaultRaycaster.enabled = false; } if (!canvas.gameObject.GetComponent()) { float zSize = 0.1f; float zScale = zSize / canvasRectTransform.localScale.z; canvasBoxCollider = canvas.gameObject.AddComponent(); canvasBoxCollider.size = new Vector3(canvasSize.x, canvasSize.y, zScale); canvasBoxCollider.isTrigger = true; } if (!canvas.gameObject.GetComponent()) { canvasRigidBody = canvas.gameObject.AddComponent(); canvasRigidBody.isKinematic = true; } } void RemoveCanvas() { var canvas = GetComponent(); if (!canvas) { return; } var defaultRaycaster = canvas.gameObject.GetComponent(); var customRaycaster = canvas.gameObject.GetComponent(); //if a custom raycaster exists then remove it if (customRaycaster) { Destroy(customRaycaster); } //If the default raycaster is disabled, then re-enable it if (defaultRaycaster && !defaultRaycaster.enabled) { defaultRaycaster.enabled = true; } if (canvasBoxCollider) { Destroy(canvasBoxCollider); } if (canvasRigidBody) { Destroy(canvasRigidBody); } } private void OnDestroy() { RemoveCanvas(); } private void OnDisable() { RemoveCanvas(); } } }