diff --git a/Assets/Scripts/2D/Geometry/Triangle2D.cs b/Assets/Scripts/2D/Geometry/Triangle2D.cs new file mode 100644 index 0000000..6d16785 --- /dev/null +++ b/Assets/Scripts/2D/Geometry/Triangle2D.cs @@ -0,0 +1,67 @@ +using UnityEngine; + +namespace UnityLibrary +{ + // if you need to run collision checks within a triangular area, the easiest + // way to do that in Unity is to use a polygon collider. this is not very + // performant. this class allows you to run those collision checks without + // the performance overhead. + + public class Triangle2D + { + Vector2[] vertices = new Vector2[3]; + + public Triangle2D(Vector2 v1, Vector2 v2, Vector2 v3) + { + Update(v1, v2, v3); + } + + // update triangle by defining all its vertices + public void Update(Vector2 v1, Vector2 v2, Vector2 v3) + { + vertices[0] = v1; + vertices[1] = v2; + vertices[2] = v3; + } + + // update triangle by redefining its origin (remaining points update relative to that) + public void Update(Vector2 v1) + { + Vector2 delta = v1 - vertices[0]; + vertices[0] = v1; + vertices[1] += delta; + vertices[2] += delta; + } + + // update triangle with rotation and pivot point + public void Update(Vector2 v1, Vector2 v2, Vector2 v3, float rotation, Vector2 pivot) + { + vertices[0] = v1.Rotate(rotation, pivot); + vertices[1] = v2.Rotate(rotation, pivot); + vertices[2] = v3.Rotate(rotation, pivot); + } + + float Sign(Vector2 p1, Vector2 p2, Vector2 p3) + { + return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y); + } + + public bool Contains(Vector2 pt, bool debug = false) + { + float d1, d2, d3; + bool has_neg, has_pos; + + d1 = Sign(pt, vertices[0], vertices[1]); + d2 = Sign(pt, vertices[1], vertices[2]); + d3 = Sign(pt, vertices[2], vertices[0]); + + has_neg = (d1 < 0) || (d2 < 0) || (d3 < 0); + has_pos = (d1 > 0) || (d2 > 0) || (d3 > 0); + + bool contains = ! (has_neg && has_pos); + + return contains; + } + } +} + diff --git a/Assets/Scripts/2D/Geometry/Triangle2D.cs.meta b/Assets/Scripts/2D/Geometry/Triangle2D.cs.meta new file mode 100644 index 0000000..db09c09 --- /dev/null +++ b/Assets/Scripts/2D/Geometry/Triangle2D.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5b3d23802c4b0df4db68d12d425fb251 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/AssetBundles/AssetBundleLoader.cs b/Assets/Scripts/AssetBundles/AssetBundleLoader.cs index d31ae28..db53c54 100644 --- a/Assets/Scripts/AssetBundles/AssetBundleLoader.cs +++ b/Assets/Scripts/AssetBundles/AssetBundleLoader.cs @@ -2,47 +2,34 @@ using UnityEngine; using UnityEngine.Networking; -// AssetBundle cache checker & loader with caching -// worsk by loading .manifest file from server and parsing hash string from it - namespace UnityLibrary { public class AssetBundleLoader : MonoBehaviour { public string assetBundleURL = "http://localhost/bundle"; + private string bundleName = "bundle"; void Start() { - //StartCoroutine(DownloadAndCache(assetBundleURL)); + StartCoroutine(DownloadAndCache(assetBundleURL)); } - /// - /// load assetbundle manifest, check hash, load actual bundle with hash parameter to use caching - /// instantiate gameobject - /// - /// full url to assetbundle file - /// optional parameter to access specific asset from assetbundle - /// IEnumerator DownloadAndCache(string bundleURL, string assetName = "") { - // Wait for the Caching system to be ready while (!Caching.ready) { yield return null; } - // if you want to always load from server, can clear cache first - // Caching.CleanCache(); + // Clear cache for previous versions of the asset bundle + Caching.ClearOtherCachedVersions(bundleName, Hash128.Parse("0")); - // get current bundle hash from server, random value added to avoid caching UnityWebRequest www = UnityWebRequest.Get(bundleURL + ".manifest?r=" + (Random.value * 9999999)); - Debug.Log("Loading manifest:" + bundleURL + ".manifest"); + Debug.Log("Loading manifest: " + bundleURL + ".manifest"); - // wait for load to finish - yield return www.Send(); + yield return www.SendWebRequest(); - // if received error, exit - if (www.isNetworkError == true) + if (www.isNetworkError) { Debug.LogError("www error: " + www.error); www.Dispose(); @@ -50,43 +37,38 @@ IEnumerator DownloadAndCache(string bundleURL, string assetName = "") yield break; } - // create empty hash string - Hash128 hashString = (default(Hash128));// new Hash128(0, 0, 0, 0); + Hash128 hashString = default(Hash128); - // check if received data contains 'ManifestFileVersion' if (www.downloadHandler.text.Contains("ManifestFileVersion")) { - // extract hash string from the received data, TODO should add some error checking here var hashRow = www.downloadHandler.text.ToString().Split("\n".ToCharArray())[5]; hashString = Hash128.Parse(hashRow.Split(':')[1].Trim()); - if (hashString.isValid == true) + if (hashString.isValid) { - // we can check if there is cached version or not - if (Caching.IsVersionCached(bundleURL, hashString) == true) + if (Caching.IsVersionCached(bundleURL, hashString)) { Debug.Log("Bundle with this hash is already cached!"); - } else + } + else { - Debug.Log("No cached version founded for this hash.."); + Debug.Log("No cached version found for this hash.."); } - } else + } + else { - // invalid loaded hash, just try loading latest bundle - Debug.LogError("Invalid hash:" + hashString); + Debug.LogError("Invalid hash: " + hashString); yield break; } - - } else + } + else { Debug.LogError("Manifest doesn't contain string 'ManifestFileVersion': " + bundleURL + ".manifest"); yield break; } - // now download the actual bundle, with hashString parameter it uses cached version if available www = UnityWebRequestAssetBundle.GetAssetBundle(bundleURL + "?r=" + (Random.value * 9999999), hashString, 0); - // wait for load to finish yield return www.SendWebRequest(); if (www.error != null) @@ -97,42 +79,26 @@ IEnumerator DownloadAndCache(string bundleURL, string assetName = "") yield break; } - // get bundle from downloadhandler AssetBundle bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle; - GameObject bundlePrefab = null; - // if no asset name is given, take the first/main asset if (assetName == "") { bundlePrefab = (GameObject)bundle.LoadAsset(bundle.GetAllAssetNames()[0]); - } else - { // use asset name to access inside bundle + } + else + { bundlePrefab = (GameObject)bundle.LoadAsset(assetName); } - // if we got something out if (bundlePrefab != null) { - - // instantiate at 0,0,0 and without rotation Instantiate(bundlePrefab, Vector3.zero, Quaternion.identity); - - /* - // fix pink shaders, NOTE: not always needed.. - foreach (Renderer r in go.GetComponentsInChildren(includeInactive: true)) - { - // FIXME: creates multiple materials, not good - var material = Shader.Find(r.material.shader.name); - r.material.shader = null; - r.material.shader = material; - }*/ } www.Dispose(); www = null; - // try to cleanup memory Resources.UnloadUnusedAssets(); bundle.Unload(false); bundle = null; diff --git a/Assets/Scripts/Camera/AutoResolution.cs b/Assets/Scripts/Camera/AutoResolution.cs new file mode 100644 index 0000000..87fd874 --- /dev/null +++ b/Assets/Scripts/Camera/AutoResolution.cs @@ -0,0 +1,58 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class AutoResolution : MonoBehaviour +{ + public int setWidth = 1440; + public int setHeight = 2560; + + private void Start() + { + // Get the main camera and its current dimensions + Camera camera = Camera.main; + Rect rect = camera.rect; + + // Calculate the scale height and width of the screen + float scaleHeight = ((float)Screen.width / Screen.height) / ((float)9 / 16); + float scaleWidth = 1f / scaleHeight; + + // Adjust the camera's dimensions based on the scale height and width + if (scaleHeight < 1) + { + rect.height = scaleHeight; + rect.y = (1f - scaleHeight) / 2f; + } + else + { + rect.width = scaleWidth; + rect.x = (1f - scaleWidth) / 2f; + } + + camera.rect = rect; + + SetResolution(); + } + + public void SetResolution() + { + // Get the current device's screen dimensions + int deviceWidth = Screen.width; + int deviceHeight = Screen.height; + + // Set the screen resolution to the desired dimensions, while maintaining aspect ratio + Screen.SetResolution(setWidth, (int)(((float)deviceHeight / deviceWidth) * setWidth), true); + + // Adjust the camera's dimensions based on the new resolution + if ((float)setWidth / setHeight < (float)deviceWidth / deviceHeight) + { + float newWidth = ((float)setWidth / setHeight) / ((float)deviceWidth / deviceHeight); + Camera.main.rect = new Rect((1f - newWidth) / 2f, 0f, newWidth, 1f); + } + else + { + float newHeight = ((float)deviceWidth / deviceHeight) / ((float)setWidth / setHeight); + Camera.main.rect = new Rect(0f, (1f - newHeight) / 2f, 1f, newHeight); // 새로운 Rect 적용 + } + } +} diff --git a/Assets/Scripts/Camera/CameraShake.cs b/Assets/Scripts/Camera/CameraShake.cs index d8814bb..48a88e6 100644 --- a/Assets/Scripts/Camera/CameraShake.cs +++ b/Assets/Scripts/Camera/CameraShake.cs @@ -1,58 +1,66 @@ using UnityEngine; using System.Collections; -// usage: attach this script into camera, call Shake() method to start -// source: http://answers.unity3d.com/answers/992509/view.html +/* + * Usage: attach this script to a camera or any other object, call Shake() method to start shaking it +* To turn off, change influence to zero +* Attach the camera to an empty game object to keep its local position and rotation +*/ namespace UnityLibrary { public class CameraShake : MonoBehaviour { - public bool shakePosition; - public bool shakeRotation; - - public float shakeIntensityMin = 0.1f; - public float shakeIntensityMax = 0.5f; - public float shakeDecay = 0.02f; + [Range(0f, 1f)] + public float shakeInfluence = 0.5f; + [Range(0f, 10f)] + public float rotationInfluence = 0f; private Vector3 OriginalPos; private Quaternion OriginalRot; - private bool isShakeRunning = false; - // call this function to start shaking - public void Shake() +/// +/// Will shake the camera with a random value between minIntensity and maxIntensity for duration +/// +/// +/// +/// + public void Shake(float minIntensity, float maxIntensity, float duration) { + if (isShakeRunning) + return; + OriginalPos = transform.position; OriginalRot = transform.rotation; - StartCoroutine("ProcessShake"); + + float shake = Random.Range(minIntensity, maxIntensity) * shakeInfluence; + duration *= shakeInfluence; + + StartCoroutine(ProcessShake(shake, duration)); } - IEnumerator ProcessShake() + IEnumerator ProcessShake(float shake, float duration) { - if (!isShakeRunning) + isShakeRunning = true; + float countdown = duration; + float initialShake = shake; + + while (countdown > 0) { - isShakeRunning = true; - float currentShakeIntensity = Random.Range(shakeIntensityMin, shakeIntensityMax); - - while (currentShakeIntensity > 0) - { - if (shakePosition) - { - transform.position = OriginalPos + Random.insideUnitSphere * currentShakeIntensity; - } - if (shakeRotation) - { - transform.rotation = new Quaternion(OriginalRot.x + Random.Range(-currentShakeIntensity, currentShakeIntensity) * .2f, - OriginalRot.y + Random.Range(-currentShakeIntensity, currentShakeIntensity) * .2f, - OriginalRot.z + Random.Range(-currentShakeIntensity, currentShakeIntensity) * .2f, - OriginalRot.w + Random.Range(-currentShakeIntensity, currentShakeIntensity) * .2f); - } - currentShakeIntensity -= shakeDecay; - yield return null; - } - - isShakeRunning = false; + countdown -= Time.deltaTime; + + float lerpIntensity = countdown / duration; + shake = Mathf.Lerp(0f, initialShake, lerpIntensity); + + transform.position = OriginalPos + Random.insideUnitSphere * shake; + transform.rotation = Quaternion.Euler(OriginalRot.eulerAngles + Random.insideUnitSphere * shake * rotationInfluence); + + yield return null; } + + transform.position = OriginalPos; + transform.rotation = OriginalRot; + isShakeRunning = false; } } } \ No newline at end of file diff --git a/Assets/Scripts/Camera/EditorCardboardCamera.cs b/Assets/Scripts/Camera/EditorCardboardCamera.cs new file mode 100644 index 0000000..c73bd45 --- /dev/null +++ b/Assets/Scripts/Camera/EditorCardboardCamera.cs @@ -0,0 +1,23 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +// editor only Google Carboard VR cam simulation with left alt + mouse + +public class EditorCardboardCamera : MonoBehaviour +{ +#if UNITY_EDITOR + Vector2 rotation = Vector2.zero; + public float speed = 3; + + void Update() + { + if (Input.GetKey(KeyCode.LeftAlt)) + { + rotation.y += Input.GetAxis("Mouse X"); + rotation.x += -Input.GetAxis("Mouse Y"); + transform.eulerAngles = (Vector2)rotation * speed; + } + } +#endif +} diff --git a/Assets/Scripts/Camera/MobileCamera.cs b/Assets/Scripts/Camera/MobileCamera.cs new file mode 100644 index 0000000..99fd6f5 --- /dev/null +++ b/Assets/Scripts/Camera/MobileCamera.cs @@ -0,0 +1,135 @@ +// https://forum.unity.com/threads/mobile-touch-to-orbit-pan-and-zoom-camera-without-fix-target-in-one-script.522607/#post-3531342 + +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class MobileCamera : MonoBehaviour +{ + public Transform target; + public Vector3 targetOffset; + public float distance = 5.0f; + public float maxDistance = 20; + public float minDistance = .6f; + public float xSpeed = 5.0f; + public float ySpeed = 5.0f; + public int yMinLimit = -80; + public int yMaxLimit = 80; + public float zoomRate = 10.0f; + public float panSpeed = 0.3f; + public float zoomDampening = 5.0f; + + private float xDeg = 0.0f; + private float yDeg = 0.0f; + private float currentDistance; + private float desiredDistance; + private Quaternion currentRotation; + private Quaternion desiredRotation; + private Quaternion rotation; + private Vector3 position; + + private Vector3 FirstPosition; + private Vector3 SecondPosition; + private Vector3 delta; + private Vector3 lastOffset; + private Vector3 lastOffsettemp; + //private Vector3 CameraPosition; + //private Vector3 Targetposition; + //private Vector3 MoveDistance; + + public float offsetSpeed = 0.03f; + + void Start() { Init(); } + void OnEnable() { Init(); } + + public void Init() + { + //If there is no target, create a temporary target at 'distance' from the cameras current viewpoint + if (!target) + { + GameObject go = new GameObject("Cam Target"); + go.transform.position = transform.position + (transform.forward * distance); + target = go.transform; + } + + distance = Vector3.Distance(transform.position, target.position); + currentDistance = distance; + desiredDistance = distance; + + //be sure to grab the current rotations as starting points. + position = transform.position; + rotation = transform.rotation; + currentRotation = transform.rotation; + desiredRotation = transform.rotation; + + //xDeg = Vector3.Angle(Vector3.right, transform.right); + //yDeg = Vector3.Angle(Vector3.up, transform.up); + + xDeg = transform.eulerAngles.y + Vector3.Angle(Vector3.right, transform.right); + yDeg = transform.eulerAngles.x + Vector3.Angle(Vector3.up, transform.up); + + } + + void LateUpdate() + { + // If Control and Alt and Middle button? ZOOM! + if (Input.touchCount == 2) + { + Touch touchZero = Input.GetTouch(0); + Touch touchOne = Input.GetTouch(1); + Vector2 touchZeroPreviousPosition = touchZero.position - touchZero.deltaPosition; + Vector2 touchOnePreviousPosition = touchOne.position - touchOne.deltaPosition; + float prevTouchDeltaMag = (touchZeroPreviousPosition - touchOnePreviousPosition).magnitude; + float TouchDeltaMag = (touchZero.position - touchOne.position).magnitude; + float deltaMagDiff = prevTouchDeltaMag - TouchDeltaMag; + desiredDistance += deltaMagDiff * Time.deltaTime * zoomRate * 0.0025f * Mathf.Abs(desiredDistance); + } + + // If middle mouse and left alt are selected? ORBIT + if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved) + { + Vector2 touchposition = Input.GetTouch(0).deltaPosition; + xDeg += touchposition.x * xSpeed * 0.002f; + yDeg -= touchposition.y * ySpeed * 0.002f; + yDeg = ClampAngle(yDeg, yMinLimit, yMaxLimit); + + } + + desiredRotation = Quaternion.Euler(yDeg, xDeg, 0); + currentRotation = transform.rotation; + rotation = Quaternion.Lerp(currentRotation, desiredRotation, Time.deltaTime * zoomDampening); + transform.rotation = rotation; + + if (Input.GetMouseButtonDown(1)) + { + FirstPosition = Input.mousePosition; + lastOffset = targetOffset; + } + + if (Input.GetMouseButton(1)) + { + SecondPosition = Input.mousePosition; + delta = SecondPosition - FirstPosition; + targetOffset = lastOffset + transform.right * delta.x * offsetSpeed + transform.up * delta.y * offsetSpeed; + + } + + ////////Orbit Position + // affect the desired Zoom distance if we roll the scrollwheel + desiredDistance = Mathf.Clamp(desiredDistance, minDistance, maxDistance); + currentDistance = Mathf.Lerp(currentDistance, desiredDistance, Time.deltaTime * zoomDampening); + position = target.position - (rotation * Vector3.forward * currentDistance); + position = position - targetOffset; + transform.position = position; + } + + private static float ClampAngle(float angle, float min, float max) + { + if (angle < -360) + angle += 360; + if (angle > 360) + angle -= 360; + return Mathf.Clamp(angle, min, max); + } +} + diff --git a/Assets/Scripts/Camera/SimpleSmoothMouseLookNewInput.cs b/Assets/Scripts/Camera/SimpleSmoothMouseLookNewInput.cs new file mode 100644 index 0000000..2864d24 --- /dev/null +++ b/Assets/Scripts/Camera/SimpleSmoothMouseLookNewInput.cs @@ -0,0 +1,260 @@ +using UnityEngine; +using UnityEngine.InputSystem; + +namespace UnityLibrary +{ + public class SimpleSmoothMouseLookNewInput : MonoBehaviour + { + [Header("Mouse Look")] + [Tooltip("Hold right mouse button down to rotate")] + public bool rotateWithRightMouse = true; + public Vector2 clampInDegrees = new Vector2(360, 180); + public bool lockCursor = false; + public Vector2 sensitivity = new Vector2(2, 2); + public Vector2 smoothing = new Vector2(3, 3); + Vector2 targetDirection; + Vector2 _mouseAbsolute; + Vector2 _smoothMouse; + + [Header("Camera Pan")] + public bool enablePanning = true; + public float panSpeed = 40; + + [Header("Camera Orbit")] + public bool enableOrbit = false; + public KeyCode orbitKey = KeyCode.LeftAlt; + [Tooltip("Set this to -1, if you dont require any mousebutton pressed for orbit")] + public int orbitMouseKey = 2; + public float orbitXSpeed = 400; + public float orbitYSpeed = 400; + Vector3 targetposition; + float orbitDistance = 10.0f; + private float xDeg = 0.0f; + private float yDeg = 0.0f; + + [Header("Camera Zoom")] + public bool scrollZoom = false; + public int zoomRate = 40; + public float zoomDampening = 5.0f; + public KeyCode zoomExtends = KeyCode.F; // whole cloud + + [Header("Camera Fly")] + public float flySpeed = 20; // default speed + public float accelerationRatio = 5; // when shift is pressed + public float slowDownRatio = 0.5f; // when ctrl is pressed + public KeyCode increaseSpeedKey = KeyCode.LeftShift; + public KeyCode decreaseSpeedKey = KeyCode.LeftControl; + public KeyCode upKey = KeyCode.E; + public KeyCode downKey = KeyCode.Q; + public string horizontalAxisKey = "Horizontal"; + public string verticalAxisKey = "Vertical"; + + public bool moveRoot = false; + Transform moveTransform; + + Camera cam; + + void Awake() + { + cam = Camera.main; + + moveTransform = moveRoot ? transform.root : transform; + } + + private void Start() + { + + } + + private void OnEnable() + { + // Set target direction to the camera's initial orientation, NOTE need to do this if you move camera manually elsewhere + targetDirection = transform.localRotation.eulerAngles; + } + + void Update() + { + Framing(); + if (MouseOrbit() == true) return; + MouseLook(); + CameraFly(); + } + + void Framing() + { + + } + + public void GetOrbitTarget() + { + targetposition = transform.forward * orbitDistance; + //orbitDistance = Vector3.Distance(transform.position, targetposition); + } + + + bool MouseOrbit() + { + // early exit, if not enabled, or no key is pressed, or if mousekey is set, but not pressed + if (enableOrbit == false || Input.GetKey(orbitKey) == false || (orbitMouseKey > -1 == true && Input.GetMouseButton(orbitMouseKey) == false)) + { + return false; + } + + orbitDistance += Input.GetAxis("Mouse ScrollWheel") * zoomRate * Time.deltaTime; + + xDeg = (Input.GetAxis("Mouse X") * orbitXSpeed); + yDeg = -(Input.GetAxis("Mouse Y") * orbitYSpeed); + transform.RotateAround(targetposition, Vector3.up, xDeg * Time.deltaTime); + transform.RotateAround(targetposition, transform.right, yDeg * Time.deltaTime); + + targetDirection = transform.rotation.eulerAngles; + + return true; + } + + static float ClampAngle(float angle, float min, float max) + { + if (angle < -360) + angle += 360; + if (angle > 360) + angle -= 360; + return Mathf.Clamp(angle, min, max); + } + + void MouseLook() + { + // Get raw mouse input for a cleaner reading on more sensitive mice. + //var mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")); + var mouseDelta = Mouse.current.delta.ReadValue() * Time.deltaTime*3; + + // panning with middle moouse button + if (enablePanning == true) + { + //if (Input.GetMouseButton(2)) + if (Mouse.current.middleButton.isPressed) + { + transform.Translate(-mouseDelta * panSpeed * Time.deltaTime, Space.Self); + GetOrbitTarget(); // update orbit target + } + } + + // Ensure the cursor is always locked when set + if (lockCursor == true) Cursor.lockState = CursorLockMode.Locked; + + //if (rotateWithRightMouse == true && !Input.GetMouseButton(1)) return; + if (rotateWithRightMouse == true && !Mouse.current.rightButton.isPressed) return; + + // Allow the script to clamp based on a desired target value. + Quaternion targetOrientation = Quaternion.Euler(targetDirection); + + // Scale input against the sensitivity setting and multiply that against the smoothing value. + mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity.x * smoothing.x, sensitivity.y * smoothing.y)); + // Interpolate mouse movement over time to apply smoothing delta. + _smoothMouse.x = Mathf.Lerp(_smoothMouse.x, mouseDelta.x, 1f / smoothing.x); + _smoothMouse.y = Mathf.Lerp(_smoothMouse.y, mouseDelta.y, 1f / smoothing.y); + // Find the absolute mouse movement value from point zero. + _mouseAbsolute += _smoothMouse; + + // Clamp and apply the local x value first, so as not to be affected by world transforms. + if (clampInDegrees.x < 360) _mouseAbsolute.x = Mathf.Clamp(_mouseAbsolute.x, -clampInDegrees.x * 0.5f, clampInDegrees.x * 0.5f); + + var xRotation = Quaternion.AngleAxis(-_mouseAbsolute.y, targetOrientation * Vector3.right); + transform.localRotation = xRotation; + + // Then clamp and apply the global y value. + if (clampInDegrees.y < 360) _mouseAbsolute.y = Mathf.Clamp(_mouseAbsolute.y, -clampInDegrees.y * 0.5f, clampInDegrees.y * 0.5f); + + var yRotation = Quaternion.AngleAxis(_mouseAbsolute.x, transform.InverseTransformDirection(Vector3.up)); + transform.localRotation *= yRotation; + transform.rotation *= targetOrientation; + } + + void CameraFly() + { + bool moved = false; + // shift was pressed down + //if (Input.GetKeyDown(increaseSpeedKey)) + if (Keyboard.current.leftShiftKey.wasPressedThisFrame) + { + flySpeed *= accelerationRatio; // increase flyspeed + } + + //if (Input.GetKeyUp(increaseSpeedKey)) + if (Keyboard.current.leftShiftKey.wasReleasedThisFrame) + { + flySpeed /= accelerationRatio; // flyspeed back to normal + } + + //if (Input.GetKeyDown(decreaseSpeedKey)) + if (Keyboard.current.leftCtrlKey.wasPressedThisFrame) + { + flySpeed *= slowDownRatio; // decrease flyspeed + } + //if (Input.GetKeyUp(decreaseSpeedKey)) + if (Keyboard.current.leftCtrlKey.wasReleasedThisFrame) + { + flySpeed /= slowDownRatio; // flyspeed back to normal + } + + var vert = -Keyboard.current.sKey.ReadValue() + Keyboard.current.wKey.ReadValue(); + if (vert != 0) + { + moveTransform.Translate(transform.forward * flySpeed * vert * Time.deltaTime, Space.World); + moved = true; + } + + var horz = -Keyboard.current.aKey.ReadValue() + Keyboard.current.dKey.ReadValue(); + if (horz != 0) + { + moveTransform.Translate(transform.right * flySpeed * horz * Time.deltaTime, Space.World); + moved = true; + } + + // annoying in editor as it works from any window +#if !UNITY_EDITOR + if (scrollZoom == true) + { + //if (Input.GetAxis("Mouse ScrollWheel") != 0) + var scrollY = Mouse.current.scroll.ReadValue().y; + if (scrollY != 0) + { + transform.Translate(transform.forward * zoomRate * scrollY * Time.deltaTime, Space.World); + moved = true; + } + } +#endif + + //if (Input.GetKey(upKey)) + if (Keyboard.current.qKey.isPressed) + { + moveTransform.Translate(moveTransform.up * flySpeed * 0.5f * Time.deltaTime, Space.World); + moved = true; + } + //else if (Input.GetKey(downKey)) + else if (Keyboard.current.eKey.isPressed) + { + moveTransform.Translate(-moveTransform.up * flySpeed * 0.5f * Time.deltaTime, Space.World); + moved = true; + } + if (moved == true) GetOrbitTarget(); + } // CameraFly() + + // https://stackoverflow.com/questions/25368259/making-an-object-fit-exactly-inside-the-camera-frustum-in-three-js + public void FocusCameraOnGameObject(Bounds b) + { + var height = b.max.y; + var width = b.max.x - b.min.x; + var vertical_FOV = cam.fieldOfView * (Mathf.PI / 180f); + var aspectRatio = Screen.width / Screen.height; + var horizontal_FOV = 2 * Mathf.Atan(Mathf.Tan(vertical_FOV / 2) * aspectRatio); + var distance_vertical = height / (2 * Mathf.Tan(vertical_FOV / 2)); + var distance_horizontal = width / (2 * Mathf.Tan(horizontal_FOV / 2)); + var z_distance = distance_vertical >= distance_horizontal ? distance_vertical : distance_horizontal; + // current viewdir + var viewDir = transform.forward; + // move camera so that object is in front + cam.transform.position = b.center - viewDir * z_distance * 2; + } + + } // class +} // namespace diff --git a/Assets/Scripts/Docs/Graphics/Graphics_Blit.cs b/Assets/Scripts/Docs/Graphics/Graphics_Blit.cs index 6760898..805f4ba 100644 --- a/Assets/Scripts/Docs/Graphics/Graphics_Blit.cs +++ b/Assets/Scripts/Docs/Graphics/Graphics_Blit.cs @@ -26,7 +26,7 @@ void OnPostRender() { // Copies source texture into destination render texture with a shader // Destination RenderTexture is null to blit directly to screen - Graphics.Blit(displayTexture, null, mat); + Graphics.Blit(displayTexture, null as RenderTexture, mat); } } } \ No newline at end of file diff --git a/Assets/Scripts/Docs/UnityEngine/NavMeshAgentExample.cs b/Assets/Scripts/Docs/UnityEngine/NavMeshAgentExample.cs new file mode 100644 index 0000000..bae418b --- /dev/null +++ b/Assets/Scripts/Docs/UnityEngine/NavMeshAgentExample.cs @@ -0,0 +1,23 @@ +// made with chatGPT + +using UnityEngine; +using UnityEngine.AI; + +namespace UnityLibrary +{ + public class NavMeshAgentExample : MonoBehaviour + { + public Transform target; + + private NavMeshAgent agent; + + void Start() + { + // Get the NavMeshAgent component on this game object + agent = GetComponent(); + + // Set the destination of the NavMeshAgent to the target Transform + agent.destination = target.position; + } + } +} diff --git a/Assets/Scripts/Drawing/DrawLine.cs b/Assets/Scripts/Drawing/DrawLine.cs index 44d6c53..6ffbfbd 100644 --- a/Assets/Scripts/Drawing/DrawLine.cs +++ b/Assets/Scripts/Drawing/DrawLine.cs @@ -53,8 +53,9 @@ protected virtual void Update() } if (Input.GetMouseButton(0)) { - Vector3 mousePosition = m_Camera.ScreenToWorldPoint(Input.mousePosition); - mousePosition.z = m_LineRenderer.transform.position.z; + var pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, lineRenderer.transform.position.z - m_Camera.transform.position.z); + Vector3 mousePosition = m_Camera.ScreenToWorldPoint(pos); + mousePosition.z = 0; if (!m_Points.Contains(mousePosition)) { m_Points.Add(mousePosition); diff --git a/Assets/Scripts/Editor/Animation.meta b/Assets/Scripts/Editor/Animation.meta new file mode 100644 index 0000000..a9393f4 --- /dev/null +++ b/Assets/Scripts/Editor/Animation.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 344c9e72d34584041b61214522912d71 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/Animation/LegacyAnimationCreator.meta b/Assets/Scripts/Editor/Animation/LegacyAnimationCreator.meta new file mode 100644 index 0000000..9fc6b69 --- /dev/null +++ b/Assets/Scripts/Editor/Animation/LegacyAnimationCreator.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e78d070eb9ba01749a33425b62b0fe5c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/Animation/LegacyAnimationCreator/LegacyAnimationCreator.cs b/Assets/Scripts/Editor/Animation/LegacyAnimationCreator/LegacyAnimationCreator.cs new file mode 100644 index 0000000..35f7ff2 --- /dev/null +++ b/Assets/Scripts/Editor/Animation/LegacyAnimationCreator/LegacyAnimationCreator.cs @@ -0,0 +1,28 @@ +using System.IO; +using UnityEditor; +using UnityEngine; + +public class LegacyAnimationCreator +{ + [MenuItem("Assets/Create/Legacy Animation", priority = 402)] + public static void CompressSelectedAnimationClips() + { + var clip = new AnimationClip(); + clip.legacy = true; + clip.name = "New Legacy Animation"; + + string path; + var selection = Selection.activeObject; + if (selection == null) + path = "Assets"; + else + path = AssetDatabase.GetAssetPath(selection.GetInstanceID()); + + path = Path.GetDirectoryName(path); + path += $"/{clip.name}.anim"; + + ProjectWindowUtil.CreateAsset(clip, path); + Selection.activeObject = clip; + EditorUtility.SetDirty(clip); + } +} \ No newline at end of file diff --git a/Assets/Scripts/Editor/Animation/LegacyAnimationCreator/LegacyAnimationCreator.cs.meta b/Assets/Scripts/Editor/Animation/LegacyAnimationCreator/LegacyAnimationCreator.cs.meta new file mode 100644 index 0000000..5bd716f --- /dev/null +++ b/Assets/Scripts/Editor/Animation/LegacyAnimationCreator/LegacyAnimationCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d536889e20faa9d47b7def4f46203b81 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/BatchTools/CopyGameObjectNames.cs b/Assets/Scripts/Editor/BatchTools/CopyGameObjectNames.cs new file mode 100644 index 0000000..40bf0d0 --- /dev/null +++ b/Assets/Scripts/Editor/BatchTools/CopyGameObjectNames.cs @@ -0,0 +1,59 @@ +// editor tool to copy names of selected GameObjects to clipboard as a list (so you can paste them in Excel or others..) + +using UnityEngine; +using UnityEditor; +using System.Text; +using System.Linq; +namespace UnityLibrary.Tools +{ + public class CopyGameObjectNames : EditorWindow + { + private string gameObjectNames = string.Empty; + + [MenuItem("Tools/Copy GameObject Names")] + public static void ShowWindow() + { + GetWindow("Copy GameObject Names"); + } + + private void OnGUI() + { + GUILayout.Label("Copy Names of Selected GameObjects", EditorStyles.boldLabel); + + if (GUILayout.Button("Fetch Names")) + { + FetchNames(); + } + + GUILayout.Label("GameObject Names:", EditorStyles.label); + gameObjectNames = EditorGUILayout.TextArea(gameObjectNames, GUILayout.Height(200)); + + if (GUILayout.Button("Copy to Clipboard")) + { + CopyToClipboard(); + } + } + + private void FetchNames() + { + StringBuilder sb = new StringBuilder(); + GameObject[] selectedObjects = Selection.gameObjects; + + // Sort the selected objects by their sibling index + var sortedObjects = selectedObjects.OrderBy(go => go.transform.GetSiblingIndex()).ToArray(); + + foreach (GameObject obj in sortedObjects) + { + sb.AppendLine(obj.name); + } + + gameObjectNames = sb.ToString(); + } + + private void CopyToClipboard() + { + EditorGUIUtility.systemCopyBuffer = gameObjectNames; + Debug.Log("GameObject names copied to clipboard."); + } + } +} diff --git a/Assets/Scripts/Editor/BatchTools/LegacyAssetUpgrader.cs b/Assets/Scripts/Editor/BatchTools/LegacyAssetUpgrader.cs new file mode 100644 index 0000000..6dfb806 --- /dev/null +++ b/Assets/Scripts/Editor/BatchTools/LegacyAssetUpgrader.cs @@ -0,0 +1,235 @@ +// NOTE updates whole selected folder (not just the ones that print warnings) + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace UnityLibrary.Editor.Tools +{ + public class LegacyAssetUpgrader : EditorWindow + { + private DefaultAsset rootFolder; + private bool includeSubfolders = true; + private Vector2 scroll; + private readonly List log = new(); + + [MenuItem("Tools/UnityLibrary/Batch/Upgrade Legacy Serialized Assets")] + public static void ShowWindow() + { + GetWindow("Asset Upgrader"); + } + + private void OnGUI() + { + EditorGUILayout.LabelField("Legacy Serialized Asset Upgrader", EditorStyles.boldLabel); + EditorGUILayout.Space(); + + EditorGUILayout.HelpBox( + "Re-saves assets and their .meta files using the current Unity serialization version.\n\n" + + "This fixes warnings such as:\n" + + "\"TextureImporter object at version 7, below the supported minimum (10)\"\n" + + "\"GameObject object at version 5, below the supported minimum (6)\"", + MessageType.Info); + + EditorGUILayout.Space(); + + rootFolder = (DefaultAsset)EditorGUILayout.ObjectField("Root Folder", rootFolder, typeof(DefaultAsset), false); + includeSubfolders = EditorGUILayout.Toggle("Include Subfolders", includeSubfolders); + + EditorGUILayout.Space(); + + using (new EditorGUI.DisabledScope(rootFolder == null)) + { + if (GUILayout.Button("Upgrade All Assets In Folder", GUILayout.Height(35))) + UpgradeFolder(); + } + + if (GUILayout.Button("Upgrade Selected Assets", GUILayout.Height(28))) + UpgradeSelected(); + + EditorGUILayout.Space(); + + if (log.Count > 0) + { + EditorGUILayout.LabelField("Log", EditorStyles.boldLabel); + + scroll = EditorGUILayout.BeginScrollView(scroll); + + foreach (string line in log) + EditorGUILayout.LabelField(line, EditorStyles.wordWrappedLabel); + + EditorGUILayout.EndScrollView(); + + if (GUILayout.Button("Clear Log")) + log.Clear(); + } + } + + private void UpgradeFolder() + { + string rootPath = AssetDatabase.GetAssetPath(rootFolder); + + if (!AssetDatabase.IsValidFolder(rootPath)) + { + Debug.LogError("Selected object is not a folder."); + return; + } + + string[] guids = AssetDatabase.FindAssets("", new[] { rootPath }); + List paths = new(); + + foreach (string guid in guids) + { + string path = AssetDatabase.GUIDToAssetPath(guid); + + if (AssetDatabase.IsValidFolder(path)) + continue; + + if (!includeSubfolders) + { + string directory = Path.GetDirectoryName(path)?.Replace("\\", "/"); + + if (!string.Equals(directory, rootPath, StringComparison.OrdinalIgnoreCase)) + continue; + } + + paths.Add(path); + } + + UpgradeAssets(paths); + } + + private void UpgradeSelected() + { + List paths = new(); + + foreach (UnityEngine.Object obj in Selection.objects) + { + string path = AssetDatabase.GetAssetPath(obj); + + if (string.IsNullOrEmpty(path)) + continue; + + if (AssetDatabase.IsValidFolder(path)) + { + string[] guids = AssetDatabase.FindAssets("", new[] { path }); + + foreach (string guid in guids) + { + string assetPath = AssetDatabase.GUIDToAssetPath(guid); + + if (!AssetDatabase.IsValidFolder(assetPath)) + paths.Add(assetPath); + } + } + else + { + paths.Add(path); + } + } + + UpgradeAssets(paths); + } + + private void UpgradeAssets(List paths) + { + if (paths.Count == 0) + { + Debug.LogWarning("No assets found."); + return; + } + + log.Clear(); + + try + { + for (int i = 0; i < paths.Count; i++) + { + string path = paths[i]; + + if (EditorUtility.DisplayCancelableProgressBar( + "Upgrading Legacy Assets", + $"{i + 1}/{paths.Count}\n{path}", + (float)i / paths.Count)) + { + log.Add("Cancelled."); + break; + } + + try + { + UpgradeAsset(path); + log.Add($"OK: {path}"); + } + catch (Exception e) + { + log.Add($"FAILED: {path} - {e.Message}"); + Debug.LogException(e); + } + } + } + finally + { + EditorUtility.ClearProgressBar(); + } + + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + + Debug.Log($"Legacy asset upgrade finished. Processed {paths.Count} assets."); + } + + private void UpgradeAsset(string path) + { + string extension = Path.GetExtension(path).ToLowerInvariant(); + + if (extension == ".prefab") + { + ResavePrefab(path); + Reserialize(path); + return; + } + + if (extension == ".unity") + { + Reserialize(path); + return; + } + + AssetImporter importer = AssetImporter.GetAtPath(path); + + if (importer != null) + { + EditorUtility.SetDirty(importer); + importer.SaveAndReimport(); + } + + Reserialize(path); + } + + private static void ResavePrefab(string path) + { + GameObject root = null; + + try + { + root = PrefabUtility.LoadPrefabContents(path); + PrefabUtility.SaveAsPrefabAsset(root, path); + } + finally + { + if (root != null) + PrefabUtility.UnloadPrefabContents(root); + } + } + + private static void Reserialize(string path) + { + AssetDatabase.ForceReserializeAssets( + new[] { path }, + ForceReserializeAssetsOptions.ReserializeAssetsAndMetadata); + } + } +} diff --git a/Assets/Scripts/Editor/BatchTools/ReplaceCharacterInGameObjectNames.cs b/Assets/Scripts/Editor/BatchTools/ReplaceCharacterInGameObjectNames.cs new file mode 100644 index 0000000..105bc74 --- /dev/null +++ b/Assets/Scripts/Editor/BatchTools/ReplaceCharacterInGameObjectNames.cs @@ -0,0 +1,69 @@ +// editor tool to replace string from selected GameObject names + +using UnityEngine; +using UnityEditor; +using UnityEditor.SceneManagement; + +namespace UnityLibrary.Tools +{ + public class ReplaceCharacterInGameObjectNames : EditorWindow + { + private string searchString = "|"; + private string replaceString = "@"; + + [MenuItem("Tools/Replace Characters in GameObject Names")] + public static void ShowWindow() + { + GetWindow("Replace Characters"); + } + + private void OnGUI() + { + GUILayout.Label("Replace Characters in Selected GameObject Names", EditorStyles.boldLabel); + + searchString = EditorGUILayout.TextField("Search String", searchString); + replaceString = EditorGUILayout.TextField("Replace String", replaceString); + + int selectedObjectCount = Selection.gameObjects.Length; + GUILayout.Label($"Selected GameObjects: {selectedObjectCount}", EditorStyles.label); + + if (GUILayout.Button("Replace")) + { + ReplaceCharacters(); + } + } + + private void ReplaceCharacters() + { + GameObject[] selectedObjects = Selection.gameObjects; + + if (selectedObjects.Length == 0) + { + Debug.LogWarning("No GameObjects selected."); + return; + } + + // Start a new undo group + Undo.IncrementCurrentGroup(); + Undo.SetCurrentGroupName("Replace Character in GameObject Names"); + int undoGroup = Undo.GetCurrentGroup(); + + foreach (GameObject obj in selectedObjects) + { + if (obj.name.Contains(searchString)) + { + Undo.RecordObject(obj, "Replace Character in GameObject Name"); + obj.name = obj.name.Replace(searchString, replaceString); + EditorUtility.SetDirty(obj); + } + } + + // End the undo group + Undo.CollapseUndoOperations(undoGroup); + + EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); + + Debug.Log($"Replaced '{searchString}' with '{replaceString}' in the names of selected GameObjects."); + } + } +} diff --git a/Assets/Scripts/Editor/BatchTools/SliderStyleCopier.cs b/Assets/Scripts/Editor/BatchTools/SliderStyleCopier.cs new file mode 100644 index 0000000..9559541 --- /dev/null +++ b/Assets/Scripts/Editor/BatchTools/SliderStyleCopier.cs @@ -0,0 +1,259 @@ +// Put this file in any folder named "Editor". +// Window: Tools > UI > Slider Style Copier +// Also available as right-click on a Slider component: Copy / Paste Slider Style + +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +using UnityEngine.UI; + +namespace UnityLibrary.UI.Tools +{ + public class SliderStyleCopier : EditorWindow + { + [SerializeField] Slider source; + [SerializeField] List targets = new List(); + + [SerializeField] bool copySlider = true; // colors, transition, target graphic, fill/handle refs + [SerializeField] bool copyRects = true; // RectTransforms of children (root excluded) + [SerializeField] bool copyGraphics = true; // Image / RawImage / Text: sprite, color, type, settings + [SerializeField] bool copyValues = false; // value / min / max / wholeNumbers + + // Never copied: script ref and event wiring (target keeps its own listeners). + static readonly HashSet AlwaysSkip = new HashSet { "m_Script", "m_OnValueChanged" }; + static readonly HashSet ValueProps = new HashSet { "m_Value", "m_MinValue", "m_MaxValue", "m_WholeNumbers" }; + + static Slider clipboard; + SerializedObject so; + Vector2 scroll; + + [MenuItem("Tools/UI/Slider Style Copier")] + static void Open() => GetWindow("Slider Copier").Show(); + + void OnEnable() => so = new SerializedObject(this); + + void OnGUI() + { + if (so == null) so = new SerializedObject(this); + so.Update(); + + EditorGUILayout.PropertyField(so.FindProperty("source"), new GUIContent("Source Slider")); + + EditorGUILayout.Space(); + scroll = EditorGUILayout.BeginScrollView(scroll); + EditorGUILayout.PropertyField(so.FindProperty("targets"), new GUIContent("Targets"), true); + EditorGUILayout.EndScrollView(); + + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(so.FindProperty("copySlider"), new GUIContent("Slider component")); + EditorGUILayout.PropertyField(so.FindProperty("copyRects"), new GUIContent("Child RectTransforms")); + EditorGUILayout.PropertyField(so.FindProperty("copyGraphics"), new GUIContent("Images / Graphics")); + EditorGUILayout.PropertyField(so.FindProperty("copyValues"), new GUIContent("Slider values (min/max/value)")); + + so.ApplyModifiedProperties(); + + EditorGUILayout.Space(); + using (new EditorGUILayout.HorizontalScope()) + { + if (GUILayout.Button("Add Selection To Targets")) AddSelectionToTargets(); + if (GUILayout.Button("Clear Targets")) { targets.Clear(); so.Update(); } + } + + EditorGUILayout.Space(); + using (new EditorGUI.DisabledScope(source == null)) + { + if (GUILayout.Button("Apply To Target List", GUILayout.Height(24))) + ApplyToMany(source, targets, Options()); + + if (GUILayout.Button("Apply To Current Selection", GUILayout.Height(24))) + ApplyToMany(source, SelectedSliders(), Options()); + } + + if (source == null) + EditorGUILayout.HelpBox("Assign a source slider. Target hierarchies must match the source hierarchy.", MessageType.Info); + } + + Opts Options() => new Opts { slider = copySlider, rects = copyRects, graphics = copyGraphics, values = copyValues }; + + void AddSelectionToTargets() + { + foreach (var s in SelectedSliders()) + if (s != source && !targets.Contains(s)) targets.Add(s); + so.Update(); + Repaint(); + } + + static List SelectedSliders() + { + var list = new List(); + foreach (var go in Selection.gameObjects) + { + var s = go.GetComponent(); + if (s != null && !list.Contains(s)) list.Add(s); + } + return list; + } + + // ---------------------------------------------------------------- context menu + + [MenuItem("CONTEXT/Slider/Copy Slider Style")] + static void ContextCopy(MenuCommand cmd) => clipboard = (Slider)cmd.context; + + [MenuItem("CONTEXT/Slider/Paste Slider Style", true)] + static bool ContextPasteValidate() => clipboard != null; + + [MenuItem("CONTEXT/Slider/Paste Slider Style")] + static void ContextPaste(MenuCommand cmd) + { + var list = SelectedSliders(); + var clicked = (Slider)cmd.context; + if (!list.Contains(clicked)) list.Add(clicked); + ApplyToMany(clipboard, list, new Opts { slider = true, rects = true, graphics = true, values = false }); + } + + // ---------------------------------------------------------------- copying + + struct Opts { public bool slider, rects, graphics, values; } + + static void ApplyToMany(Slider src, List list, Opts opts) + { + if (src == null || list == null) return; + + int group = Undo.GetCurrentGroup(); + Undo.SetCurrentGroupName("Copy Slider Style"); + + int done = 0; + foreach (var dst in list) + { + if (dst == null || dst == src) continue; + Undo.RegisterFullObjectHierarchyUndo(dst.gameObject, "Copy Slider Style"); + CopyNode(src.transform, dst.transform, src.transform, dst.transform, opts); + done++; + } + + Undo.CollapseUndoOperations(group); + Debug.Log($"Slider Style Copier: copied '{src.name}' to {done} slider(s).", src); + } + + static void CopyNode(Transform s, Transform d, Transform sRoot, Transform dRoot, Opts opts) + { + if (opts.rects && s != sRoot && s is RectTransform sr && d is RectTransform dr) + CopyRect(sr, dr); + + if (opts.graphics) + CopySameTypeComponents(s, d, sRoot, dRoot, null); + + if (opts.slider) + CopySameTypeComponents(s, d, sRoot, dRoot, opts.values ? null : ValueProps); + + if (s.childCount != d.childCount) + Debug.LogWarning($"Slider Style Copier: child count mismatch at '{d.name}' ({s.childCount} vs {d.childCount}). Extra children are ignored.", d); + + int n = Mathf.Min(s.childCount, d.childCount); + for (int i = 0; i < n; i++) + CopyNode(s.GetChild(i), d.GetChild(i), sRoot, dRoot, opts); + } + + static void CopyRect(RectTransform s, RectTransform d) + { + Undo.RecordObject(d, "Copy Slider Style"); + d.anchorMin = s.anchorMin; + d.anchorMax = s.anchorMax; + d.pivot = s.pivot; + d.anchoredPosition3D = s.anchoredPosition3D; + d.sizeDelta = s.sizeDelta; + d.localRotation = s.localRotation; + d.localScale = s.localScale; + PrefabUtility.RecordPrefabInstancePropertyModifications(d); + } + + static void CopySameTypeComponents(Transform s, Transform d, Transform sRoot, Transform dRoot, HashSet extraSkip) where T : Component + { + var src = s.GetComponents(); + var dst = d.GetComponents(); + for (int i = 0; i < src.Length && i < dst.Length; i++) + { + if (src[i].GetType() != dst[i].GetType()) continue; + CopyComponent(src[i], dst[i], sRoot, dRoot, extraSkip); + } + } + + // Serialized copy: covers every inspector field (colors, transition, sprite state, + // image type/fill settings, ...) without listing them one by one. + // Object references pointing inside the source hierarchy are remapped to the + // matching object in the target hierarchy; asset references are copied as-is. + static void CopyComponent(Component src, Component dst, Transform sRoot, Transform dRoot, HashSet extraSkip) + { + var from = new SerializedObject(src); + var to = new SerializedObject(dst); + var it = from.GetIterator(); + + bool enterChildren = true; + while (it.NextVisible(enterChildren)) + { + enterChildren = true; + + if (AlwaysSkip.Contains(it.propertyPath) || (extraSkip != null && extraSkip.Contains(it.propertyPath))) + { + enterChildren = false; // do not descend into skipped branches + continue; + } + + var tp = to.FindProperty(it.propertyPath); + if (tp == null) continue; + + if (it.propertyType == SerializedPropertyType.ObjectReference) + tp.objectReferenceValue = Remap(it.objectReferenceValue, sRoot, dRoot); + else if (!it.hasVisibleChildren) + to.CopyFromSerializedProperty(it); + } + + to.ApplyModifiedProperties(); // registers undo + prefab modifications + } + + static Object Remap(Object value, Transform sRoot, Transform dRoot) + { + if (value == null) return null; + + Transform t = value as Transform; + if (t == null && value is Component c) t = c.transform; + if (t == null && value is GameObject go) t = go.transform; + if (t == null) return value; // asset (sprite, material, ...) + if (!IsUnder(t, sRoot)) return value; // outside the slider hierarchy, keep as is + + var mapped = FindMatching(t, sRoot, dRoot); + if (mapped == null) return value; + + if (value is GameObject) return mapped.gameObject; + if (value is Transform) return mapped; + return mapped.GetComponent(value.GetType()); + } + + static bool IsUnder(Transform t, Transform root) + { + for (var p = t; p != null; p = p.parent) + if (p == root) return true; + return false; + } + + // Same sibling-index path under the target root. + static Transform FindMatching(Transform node, Transform sRoot, Transform dRoot) + { + var path = new List(); + for (var t = node; t != sRoot; t = t.parent) + { + if (t == null) return null; + path.Add(t.GetSiblingIndex()); + } + path.Reverse(); + + var d = dRoot; + for (int i = 0; i < path.Count; i++) + { + if (path[i] >= d.childCount) return null; + d = d.GetChild(path[i]); + } + return d; + } + } +} diff --git a/Assets/Scripts/Editor/BuildProcess/PostBuildCopyEmptyFolders.cs b/Assets/Scripts/Editor/BuildProcess/PostBuildCopyEmptyFolders.cs new file mode 100644 index 0000000..186265b --- /dev/null +++ b/Assets/Scripts/Editor/BuildProcess/PostBuildCopyEmptyFolders.cs @@ -0,0 +1,54 @@ +using System.IO; +using UnityEditor; +using UnityEditor.Callbacks; +using UnityEngine; + +// copies empty StreamingAssets/ folders into build, as they are not automatically included + +namespace UnityLibrary +{ + public class PostBuildCopyEmptyFolders : MonoBehaviour + { + [PostProcessBuildAttribute(1)] + public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) + { + // only for windows + if (target != BuildTarget.StandaloneWindows) return; + + Debug.Log("### POSTBUILD : COPY EMPTY STREAMINGASSETS-FOLDERS ###"); + Debug.Log("Build done: " + pathToBuiltProject); + + // get output root + var root = Path.GetDirectoryName(pathToBuiltProject); + var appName = Path.GetFileNameWithoutExtension(pathToBuiltProject); + + // copy empty streaming asset folders to build + var sourcePath = Application.streamingAssetsPath; + var targetPath = Path.Combine(root, appName + "_Data", "StreamingAssets"); + //Debug.Log("sourcePath= "+ sourcePath); + //Debug.Log("targetPath= " + targetPath); + CopyFolderStructure(sourcePath, targetPath); + } + + // recursive folder copier + static public void CopyFolderStructure(string sourceFolder, string destFolder) + { + if (Directory.Exists(destFolder)) + { + + } + else + { + Directory.CreateDirectory(destFolder); + } + + string[] folders = Directory.GetDirectories(sourceFolder); + foreach (string folder in folders) + { + string name = Path.GetFileName(folder); + string dest = Path.Combine(destFolder, name); + CopyFolderStructure(folder, dest); + } + } + } +} diff --git a/Assets/Scripts/Editor/BuildProcess/SingleExePostProcessor.cs b/Assets/Scripts/Editor/BuildProcess/SingleExePostProcessor.cs new file mode 100644 index 0000000..b902720 --- /dev/null +++ b/Assets/Scripts/Editor/BuildProcess/SingleExePostProcessor.cs @@ -0,0 +1,122 @@ +// builds single standalone exe from your Unity build (using 7-Zip SFX module) +// Note: Change those hardcoded 7zip paths for you +// Note: Download SDK package for the 7zSD.sfx files https://www.7-zip.org/download.html +// Warning: This copies all build folder output there, you might not want debug symbols or other data +// Note: You could make it customize the exe icon also (with external tool calls to create .ico from project icon and assign it) + +using UnityEditor; +using UnityEditor.Callbacks; +using System; +using System.Diagnostics; +using System.IO; +using System.Text; + +namespace UnityLibrary.BuildTools +{ + public static class SingleExePostProcessor + { + private const string SevenZipExe = @"C:\Program Files\7-Zip\7z.exe"; + private const string SevenZipSfx = @"C:\sdk\lzma2603\bin\7zSD.sfx"; + + [PostProcessBuild(1000)] + public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject) + { + if (target != BuildTarget.StandaloneWindows64) + return; + + string buildExe = Path.GetFullPath(pathToBuiltProject); + string buildDirectory = Path.GetDirectoryName(buildExe); + string exeName = Path.GetFileName(buildExe); + string gameName = Path.GetFileNameWithoutExtension(buildExe); + + if (buildDirectory == null) + return; + + if (!File.Exists(SevenZipExe)) + { + UnityEngine.Debug.LogError("7-Zip not found: " + SevenZipExe); + return; + } + + if (!File.Exists(SevenZipSfx)) + { + UnityEngine.Debug.LogError("7-Zip SFX module not found: " + SevenZipSfx); + return; + } + + string tempDirectory = Path.Combine(Path.GetTempPath(), "UnitySingleExe_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDirectory); + + string archivePath = Path.Combine(tempDirectory, "game.7z"); + string configPath = Path.Combine(tempDirectory, "config.txt"); + string outputExe = Path.Combine(Directory.GetParent(buildDirectory)?.FullName ?? buildDirectory, gameName + "_Standalone.exe"); + + try + { + CreateArchive(buildDirectory, archivePath); + + string config = ";!@Install@!UTF-8!\r\n" + "Title=\"" + gameName + "\"\r\n" + "RunProgram=\"" + exeName + "\"\r\n" + "GUIMode=\"2\"\r\n" + ";!@InstallEnd@!\r\n"; + + File.WriteAllText(configPath, config, new UTF8Encoding(false)); + + using (FileStream output = File.Create(outputExe)) + { + AppendFile(output, SevenZipSfx); + AppendFile(output, configPath); + AppendFile(output, archivePath); + } + + UnityEngine.Debug.Log("Single EXE created: " + outputExe); + } + catch (Exception e) + { + UnityEngine.Debug.LogException(e); + } + finally + { + try + { + Directory.Delete(tempDirectory, true); + } + catch + { + } + } + } + + private static void CreateArchive(string buildDirectory, string archivePath) + { + ProcessStartInfo psi = new ProcessStartInfo + { + FileName = SevenZipExe, + WorkingDirectory = buildDirectory, + Arguments = "a -t7z -mx=5 \"" + archivePath + "\" \"*\"", + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + + using Process process = Process.Start(psi); + + if (process == null) + throw new Exception("Could not start 7-Zip."); + + string stdout = process.StandardOutput.ReadToEnd(); + string stderr = process.StandardError.ReadToEnd(); + + process.WaitForExit(); + + if (process.ExitCode != 0) + { + throw new Exception("7-Zip failed.\n" + stdout + "\n" + stderr); + } + } + + private static void AppendFile(Stream destination, string file) + { + using FileStream source = File.OpenRead(file); + source.CopyTo(destination); + } + } +} diff --git a/Assets/Scripts/Editor/ContextMenu/BoxColliderFitChildren.cs b/Assets/Scripts/Editor/ContextMenu/BoxColliderFitChildren.cs index 58f7b0d..ce3f298 100644 --- a/Assets/Scripts/Editor/ContextMenu/BoxColliderFitChildren.cs +++ b/Assets/Scripts/Editor/ContextMenu/BoxColliderFitChildren.cs @@ -1,7 +1,3 @@ -// Adjust Box Collider to fit child meshes inside -// Usage: You have empty parent transform, with child meshes inside, add box collider to parent then use this -// NOTE: Doesnt work if root transform is rotated - using UnityEngine; using UnityEditor; @@ -10,37 +6,66 @@ namespace UnityLibrary public class BoxColliderFitChildren : MonoBehaviour { [MenuItem("CONTEXT/BoxCollider/Fit to Children")] - static void FixSize(MenuCommand command) + static void FitColliderToChildren(MenuCommand command) { BoxCollider col = (BoxCollider)command.context; - // record undo + // Record undo Undo.RecordObject(col.transform, "Fit Box Collider To Children"); - // get child mesh bounds - var b = GetRecursiveMeshBounds(col.gameObject); + // Get world-space bounds of all child meshes + var worldBounds = GetRecursiveMeshBounds(col.gameObject); + + if (worldBounds.size == Vector3.zero) + { + Debug.LogWarning("No valid meshes found to fit the BoxCollider."); + return; + } + + // Convert world-space center to local space + Vector3 localCenter = col.transform.InverseTransformPoint(worldBounds.center); + + // Convert world-space size to local space + Vector3 localSize = col.transform.InverseTransformVector(worldBounds.size); + + // Ensure size is positive + localSize = new Vector3(Mathf.Abs(localSize.x), Mathf.Abs(localSize.y), Mathf.Abs(localSize.z)); + + // Fix potential center flipping + if (Vector3.Dot(col.transform.right, Vector3.right) < 0) + { + localCenter.x = -localCenter.x; + } + if (Vector3.Dot(col.transform.up, Vector3.up) < 0) + { + localCenter.y = -localCenter.y; + } + if (Vector3.Dot(col.transform.forward, Vector3.forward) < 0) + { + localCenter.z = -localCenter.z; + } - // set collider local center and size - col.center = col.transform.root.InverseTransformVector(b.center) - col.transform.position; - col.size = b.size; + // Apply to collider + col.center = localCenter; + col.size = localSize; } public static Bounds GetRecursiveMeshBounds(GameObject go) { - var r = go.GetComponentsInChildren(); - if (r.Length > 0) - { - var b = r[0].bounds; - for (int i = 1; i < r.Length; i++) - { - b.Encapsulate(r[i].bounds); - } - return b; - } - else // TODO no renderers + Renderer[] renderers = go.GetComponentsInChildren(); + + if (renderers.Length == 0) + return new Bounds(); + + // Start with the first renderer’s bounds in world space + Bounds worldBounds = renderers[0].bounds; + + for (int i = 1; i < renderers.Length; i++) { - return new Bounds(Vector3.one, Vector3.one); + worldBounds.Encapsulate(renderers[i].bounds); } + + return worldBounds; } } } diff --git a/Assets/Scripts/Editor/ContextMenu/LineRendererToLocalSpace.cs b/Assets/Scripts/Editor/ContextMenu/LineRendererToLocalSpace.cs new file mode 100644 index 0000000..6cc6cc7 --- /dev/null +++ b/Assets/Scripts/Editor/ContextMenu/LineRendererToLocalSpace.cs @@ -0,0 +1,60 @@ +// converts line renderer points from world space to local space + +using UnityEngine; +using UnityEditor; +using UnityEditor.SceneManagement; + +namespace UnityLibrary.ContextMenu +{ + public static class LineRendererToLocalSpace + { + private const string MenuPath = "CONTEXT/LineRenderer/Convert Points To Local Space"; + + [MenuItem(MenuPath, true)] + private static bool Validate(MenuCommand command) + { + return command != null && command.context is LineRenderer; + } + + [MenuItem(MenuPath)] + private static void Convert(MenuCommand command) + { + var lr = (LineRenderer)command.context; + if (lr == null) return; + + int count = lr.positionCount; + if (count == 0) return; + + Transform t = lr.transform; + + Undo.RecordObject(lr, "Convert LineRenderer To Local Space"); + + // Get current positions in world space no matter what mode it's in. + Vector3[] world = new Vector3[count]; + if (lr.useWorldSpace) + { + lr.GetPositions(world); + } + else + { + Vector3[] local = new Vector3[count]; + lr.GetPositions(local); + for (int i = 0; i < count; i++) + world[i] = t.TransformPoint(local[i]); + } + + // Convert world -> local, switch mode, write back. + Vector3[] newLocal = new Vector3[count]; + for (int i = 0; i < count; i++) + newLocal[i] = t.InverseTransformPoint(world[i]); + + lr.useWorldSpace = false; + lr.SetPositions(newLocal); + + EditorUtility.SetDirty(lr); + + if (!Application.isPlaying) + EditorSceneManager.MarkSceneDirty(lr.gameObject.scene); + } + } +} diff --git a/Assets/Scripts/Editor/ContextMenu/LineRendererToWorldSpace.cs b/Assets/Scripts/Editor/ContextMenu/LineRendererToWorldSpace.cs new file mode 100644 index 0000000..90cc2d2 --- /dev/null +++ b/Assets/Scripts/Editor/ContextMenu/LineRendererToWorldSpace.cs @@ -0,0 +1,54 @@ +// converts LineRenderer points from local space to world space via context menu in Unity Editor + +using UnityEngine; +using UnityEditor; +using UnityEditor.SceneManagement; + +namespace UnityLibrary.ContextMenu +{ + public static class LineRendererToWorldSpace + { + private const string MenuPath = "CONTEXT/LineRenderer/Convert Points To World Space"; + + [MenuItem(MenuPath, true)] + private static bool Validate(MenuCommand command) + { + return command != null && command.context is LineRenderer; + } + + [MenuItem(MenuPath)] + private static void Convert(MenuCommand command) + { + var lr = (LineRenderer)command.context; + if (lr == null) return; + + if (lr.useWorldSpace) + { + Debug.Log("LineRenderer is already using World Space."); + return; + } + + int count = lr.positionCount; + if (count == 0) return; + + Transform t = lr.transform; + + Undo.RecordObject(lr, "Convert LineRenderer To World Space"); + + Vector3[] local = new Vector3[count]; + lr.GetPositions(local); + + Vector3[] world = new Vector3[count]; + for (int i = 0; i < count; i++) + world[i] = t.TransformPoint(local[i]); + + lr.useWorldSpace = true; + lr.SetPositions(world); + + EditorUtility.SetDirty(lr); + + if (!Application.isPlaying) + EditorSceneManager.MarkSceneDirty(lr.gameObject.scene); + } + } +} diff --git a/Assets/Scripts/Editor/ContextMenu/MeshRendererSize.cs b/Assets/Scripts/Editor/ContextMenu/MeshRendererSize.cs new file mode 100644 index 0000000..48e381b --- /dev/null +++ b/Assets/Scripts/Editor/ContextMenu/MeshRendererSize.cs @@ -0,0 +1,28 @@ + +using UnityEditor; +using UnityEngine; + +namespace UnityLibrary.EditorTools +{ + public static class MeshRendererSize + { + [MenuItem("CONTEXT/MeshRenderer/Get Size")] + private static void GetSize(MenuCommand command) + { + MeshRenderer renderer = (MeshRenderer)command.context; + + Debug.Log( + $"Renderer size (local): {FormatSize(renderer.localBounds.size)}\n" + + $"Bounds size (world): {FormatSize(renderer.bounds.size)}", + renderer + ); + } + + private static string FormatSize(Vector3 size) + { + return $"X: {size.x:F3}, " + + $"Y: {size.y:F3}, " + + $"Z: {size.z:F3}"; + } + } +} diff --git a/Assets/Scripts/Editor/CustomInspector/CustomRectTransformCopyInspector.cs b/Assets/Scripts/Editor/CustomInspector/CustomRectTransformCopyInspector.cs new file mode 100644 index 0000000..0a5de2b --- /dev/null +++ b/Assets/Scripts/Editor/CustomInspector/CustomRectTransformCopyInspector.cs @@ -0,0 +1,114 @@ +#if UNITY_EDITOR +using System; +using System.Reflection; +using UnityEngine; + +namespace UnityEditor +{ + [CustomEditor(typeof(RectTransform), true)] + [CanEditMultipleObjects] + public class CustomRectTransformCopyInspector : Editor + { + // Unity's built-in editor + Editor defaultEditor = null; + RectTransform rectTransform; + + private static RectTransformData copiedData; + + void OnEnable() + { + // Use reflection to get the default Unity RectTransform editor + defaultEditor = Editor.CreateEditor(targets, Type.GetType("UnityEditor.RectTransformEditor, UnityEditor")); + rectTransform = target as RectTransform; + } + + void OnDisable() + { + // Destroy the default editor to avoid memory leaks + if (defaultEditor != null) + { + MethodInfo disableMethod = defaultEditor.GetType().GetMethod("OnDisable", + BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + if (disableMethod != null) + disableMethod.Invoke(defaultEditor, null); + + DestroyImmediate(defaultEditor); + } + } + + public override void OnInspectorGUI() + { + // Draw Unity's default RectTransform Inspector + defaultEditor.OnInspectorGUI(); + + // Add Copy and Paste buttons + EditorGUILayout.Space(); + GUILayout.BeginHorizontal(); + + if (GUILayout.Button("C", GUILayout.Width(30))) // Copy + { + CopyRectTransform(rectTransform); + } + + if (GUILayout.Button("P", GUILayout.Width(30))) // Paste + { + PasteRectTransform(rectTransform); + } + + GUILayout.EndHorizontal(); + } + + private void CopyRectTransform(RectTransform rectTransform) + { + copiedData = new RectTransformData(rectTransform); + Debug.Log("RectTransform copied!"); + } + + private void PasteRectTransform(RectTransform rectTransform) + { + if (copiedData == null) + { + Debug.LogWarning("No RectTransform data to paste!"); + return; + } + + Undo.RecordObject(rectTransform, "Paste RectTransform"); + + copiedData.ApplyTo(rectTransform); + Debug.Log("RectTransform pasted!"); + + EditorUtility.SetDirty(rectTransform); + } + + private class RectTransformData + { + public Vector2 anchorMin; + public Vector2 anchorMax; + public Vector2 anchoredPosition; + public Vector2 sizeDelta; + public Vector2 pivot; + public Quaternion rotation; + + public RectTransformData(RectTransform rectTransform) + { + anchorMin = rectTransform.anchorMin; + anchorMax = rectTransform.anchorMax; + anchoredPosition = rectTransform.anchoredPosition; + sizeDelta = rectTransform.sizeDelta; + pivot = rectTransform.pivot; + rotation = rectTransform.rotation; + } + + public void ApplyTo(RectTransform rectTransform) + { + rectTransform.anchorMin = anchorMin; + rectTransform.anchorMax = anchorMax; + rectTransform.anchoredPosition = anchoredPosition; + rectTransform.sizeDelta = sizeDelta; + rectTransform.pivot = pivot; + rectTransform.rotation = rotation; + } + } + } +} +#endif diff --git a/Assets/Scripts/Editor/CustomInspector/CustomRectTransformInspector.cs b/Assets/Scripts/Editor/CustomInspector/CustomRectTransformInspector.cs new file mode 100644 index 0000000..02c51af --- /dev/null +++ b/Assets/Scripts/Editor/CustomInspector/CustomRectTransformInspector.cs @@ -0,0 +1,294 @@ +// source https://gist.github.com/GieziJo/f80bcb24c4caa68ebfb204148ccd4b18 +// =============================== +// AUTHOR : J. Giezendanner +// CREATE DATE : 12.03.2020 +// MODIFIED DATE : +// PURPOSE : Adds helper functions to the RectTransform to align the rect to the anchors and vise-versa +// SPECIAL NOTES : Sources for certain informations: +// Display anchors gizmos: +// https://forum.unity.com/threads/recttransform-custom-editor-ontop-of-unity-recttransform-custom-editor.455925/ +// Draw default inspector: +// https://forum.unity.com/threads/extending-instead-of-replacing-built-in-inspectors.407612/ +// =============================== +// Change History: +//================================== + +#if UNITY_EDITOR +using System; +using System.Reflection; +using UnityEditor.SceneManagement; +using UnityEngine; + + +namespace UnityEditor +{ + [CustomEditor(typeof(RectTransform), true)] + [CanEditMultipleObjects] + public class CustomRectTransformInspector : Editor + { + //Unity's built-in editor + Editor defaultEditor = null; + RectTransform rectTransform; + + bool rect2Anchors_foldout = false; + bool anchors2Rect_foldout = false; + bool rect2Anchors__previousState = false; + bool anchors2Rect_previousState = false; + + private bool playerPrefsChecked = false; + + void OnEnable() + { + //When this inspector is created, also create the built-in inspector + defaultEditor = Editor.CreateEditor(targets, Type.GetType("UnityEditor.RectTransformEditor, UnityEditor")); + rectTransform = target as RectTransform; + } + + void OnDisable() + { + //When OnDisable is called, the default editor we created should be destroyed to avoid memory leakage. + //Also, make sure to call any required methods like OnDisable + + if (defaultEditor != null) + { + MethodInfo disableMethod = defaultEditor.GetType().GetMethod("OnDisable", + BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + if (disableMethod != null) + disableMethod.Invoke(defaultEditor, null); + DestroyImmediate(defaultEditor); + } + } + + void checkPlayerPrefs() + { + rect2Anchors_foldout = PlayerPrefs.GetInt("giezi_tools_rect2Anchors_foldout_bool", 0) != 0; + anchors2Rect_foldout = PlayerPrefs.GetInt("giezi_tools_anchors2Rect_foldout_bool", 0) != 0; + + rect2Anchors__previousState = rect2Anchors_foldout; + anchors2Rect_previousState = anchors2Rect_foldout; + } + + + public override void OnInspectorGUI() + { + if (!playerPrefsChecked) + { + checkPlayerPrefs(); + playerPrefsChecked = true; + } + + defaultEditor.OnInspectorGUI(); + + + if (rectTransform.parent != null) + { + var centerButtonStyle = new GUIStyle(GUI.skin.button); + centerButtonStyle.fontStyle = FontStyle.Bold; + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Helper Functions", EditorStyles.boldLabel); + + rect2Anchors_foldout = EditorGUILayout.Foldout(rect2Anchors_foldout, "Set Rect to Anchors"); + + if (rect2Anchors_foldout) + { + GUILayout.BeginHorizontal(); + GUILayout.BeginVertical(); + if (GUILayout.Button("Top Left")) + setRectValue("topLeft"); + if (GUILayout.Button("Left")) + setRectValue("left"); + if (GUILayout.Button("Bottom Left")) + setRectValue("bottomLeft"); + GUILayout.EndVertical(); + GUILayout.BeginVertical(); + if (GUILayout.Button("Top")) + setRectValue("top"); + if (GUILayout.Button("All", centerButtonStyle)) + setRectValue("all"); + if (GUILayout.Button("Bottom")) + setRectValue("bottom"); + GUILayout.EndVertical(); + GUILayout.BeginVertical(); + if (GUILayout.Button("Top Right")) + setRectValue("topRight"); + if (GUILayout.Button("Right")) + setRectValue("right"); + if (GUILayout.Button("Bottom Right")) + setRectValue("bottomRight"); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } + + anchors2Rect_foldout = EditorGUILayout.Foldout(anchors2Rect_foldout, "Set Anchors to Rect"); + + if (anchors2Rect_foldout) + { + GUILayout.BeginHorizontal(); + GUILayout.BeginVertical(); + if (GUILayout.Button("Top Left")) + setAnchorsToRect("topLeft"); + if (GUILayout.Button("Left")) + setAnchorsToRect("left"); + if (GUILayout.Button("Bottom Left")) + setAnchorsToRect("bottomLeft"); + GUILayout.EndVertical(); + GUILayout.BeginVertical(); + if (GUILayout.Button("Top")) + setAnchorsToRect("top"); + if (GUILayout.Button("All", centerButtonStyle)) + setAnchorsToRect("all"); + if (GUILayout.Button("Bottom")) + setAnchorsToRect("bottom"); + GUILayout.EndVertical(); + GUILayout.BeginVertical(); + if (GUILayout.Button("Top Right")) + setAnchorsToRect("topRight"); + if (GUILayout.Button("Right")) + setAnchorsToRect("right"); + if (GUILayout.Button("Bottom Right")) + setAnchorsToRect("bottomRight"); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } + + + if (rect2Anchors_foldout != rect2Anchors__previousState) + { + rect2Anchors__previousState = rect2Anchors_foldout; + PlayerPrefs.SetInt("giezi_tools_rect2Anchors_foldout_bool", rect2Anchors_foldout ? 1 : 0); + } + + if (anchors2Rect_foldout != anchors2Rect_previousState) + { + anchors2Rect_previousState = anchors2Rect_foldout; + PlayerPrefs.SetInt("giezi_tools_anchors2Rect_foldout_bool", anchors2Rect_foldout ? 1 : 0); + } + } + } + + + private void OnSceneGUI() + { + MethodInfo onSceneGUI_Method = defaultEditor.GetType() + .GetMethod("OnSceneGUI", BindingFlags.NonPublic | BindingFlags.Instance); + onSceneGUI_Method.Invoke(defaultEditor, null); + } + + + private void setAnchorsToRect(string field) + { + Vector2 anchorMax = new Vector2(); + Vector2 anchorMin = new Vector2(); + var parent = rectTransform.parent; + anchorMin.x = rectTransform.offsetMin.x / parent.GetComponent().rect.size.x; + anchorMin.y = rectTransform.offsetMin.y / parent.GetComponent().rect.size.y; + anchorMax.x = rectTransform.offsetMax.x / parent.GetComponent().rect.size.x; + anchorMax.y = rectTransform.offsetMax.y / parent.GetComponent().rect.size.y; + + + switch (field) + { + case "topLeft": + anchorMax.x = 0; + rectTransform.anchorMax += anchorMax; + rectTransform.offsetMax = new Vector2(rectTransform.offsetMax.x, 0); + + anchorMin.y = 0; + rectTransform.anchorMin += anchorMin; + rectTransform.offsetMin = new Vector2(0, rectTransform.offsetMin.y); + break; + case "top": + anchorMax.x = 0; + rectTransform.anchorMax += anchorMax; + rectTransform.offsetMax = new Vector2(rectTransform.offsetMax.x, 0); + break; + case "topRight": + rectTransform.anchorMax += anchorMax; + rectTransform.offsetMax = Vector2.zero; + break; + case "bottomLeft": + rectTransform.anchorMin += anchorMin; + rectTransform.offsetMin = Vector2.zero; + break; + case "bottom": + anchorMin.x = 0; + rectTransform.anchorMin += anchorMin; + rectTransform.offsetMin = new Vector2(rectTransform.offsetMin.x, 0); + break; + case "bottomRight": + anchorMin.x = 0; + rectTransform.anchorMin += anchorMin; + rectTransform.offsetMin = new Vector2(rectTransform.offsetMin.x, 0); + anchorMax.y = 0; + rectTransform.anchorMax += anchorMax; + rectTransform.offsetMax = new Vector2(0, rectTransform.offsetMax.y); + break; + case "left": + anchorMin.y = 0; + rectTransform.anchorMin += anchorMin; + rectTransform.offsetMin = new Vector2(0, rectTransform.offsetMin.y); + break; + case "right": + anchorMax.y = 0; + rectTransform.anchorMax += anchorMax; + rectTransform.offsetMax = new Vector2(0, rectTransform.offsetMax.y); + break; + case "all": + rectTransform.anchorMax += anchorMax; + rectTransform.anchorMin += anchorMin; + rectTransform.offsetMin = Vector2.zero; + rectTransform.offsetMax = Vector2.zero; + break; + } + + handleChange(); + } + + + private void setRectValue(string field) + { + switch (field) + { + case "topLeft": + rectTransform.offsetMax = new Vector2(rectTransform.offsetMax.x, 0); + rectTransform.offsetMin = new Vector2(0, rectTransform.offsetMin.y); + break; + case "top": + rectTransform.offsetMax = new Vector2(rectTransform.offsetMax.x, 0); + break; + case "topRight": + rectTransform.offsetMax = Vector2.zero; + break; + case "bottomLeft": + rectTransform.offsetMin = Vector2.zero; + break; + case "bottom": + rectTransform.offsetMin = new Vector2(rectTransform.offsetMin.x, 0); + break; + case "bottomRight": + rectTransform.offsetMin = new Vector2(rectTransform.offsetMin.x, 0); + rectTransform.offsetMax = new Vector2(0, rectTransform.offsetMax.y); + break; + case "left": + rectTransform.offsetMin = new Vector2(0, rectTransform.offsetMin.y); + break; + case "right": + rectTransform.offsetMax = new Vector2(0, rectTransform.offsetMax.y); + break; + case "all": + rectTransform.offsetMin = new Vector2(0, 0); + rectTransform.offsetMax = new Vector2(0, 0); + break; + } + + handleChange(); + } + + private void handleChange() + { + EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); + } + } +} +#endif diff --git a/Assets/Scripts/Editor/CustomInspector/TransformEditor.cs b/Assets/Scripts/Editor/CustomInspector/TransformEditor.cs new file mode 100644 index 0000000..152989e --- /dev/null +++ b/Assets/Scripts/Editor/CustomInspector/TransformEditor.cs @@ -0,0 +1,436 @@ +// source https://gist.github.com/unitycoder/e5e6384f087639c0d9edc93aa3820468 + +using UnityEngine; +using UnityEditor; + +namespace OddTales.Framework.Core.EditorExtension +{ + /// + /// Custom inspector for Transform component. Using only DrawDefaultInspector would give different display. + /// Script based on Unity wiki implementation : https://wiki.unity3d.com/index.php/TransformInspector + /// Buttons to reset, copy, paste Transform values. + /// Context menu to round/truncate values, hide/show tools. + /// + [CanEditMultipleObjects, CustomEditor(typeof(Transform))] + public class TransformEditor : Editor + { + private const float FIELD_WIDTH = 212.0f; + private const bool WIDE_MODE = true; + + private const float POSITION_MAX = 100000.0f; + + private static GUIContent positionGUIContent = new GUIContent(LocalString("Position")); + private static GUIContent rotationGUIContent = new GUIContent(LocalString("Rotation")); + private static GUIContent scaleGUIContent = new GUIContent(LocalString("Scale")); + + private static string positionWarningText = LocalString("Due to floating-point precision limitations, it is recommended to bring the world coordinates of the GameObject within a smaller range."); + + private SerializedProperty positionProperty, rotationProperty, scaleProperty; + + private static Vector3? positionClipboard = null; + private static Quaternion? rotationClipboard = null; + private static Vector3? scaleClipboard = null; + + private const string SHOW_TOOLS_KEY = "TransformEditor_ShowTools"; + private const string SHOW_RESET_TOOLS_KEY = "TransformEditor_ShowResetTools"; + private const string SHOW_PASTE_TOOLS_KEY = "TransformEditor_ShowPasteTools"; + private const string SHOW_ADVANCED_PASTE_TOOLS_KEY = "TransformEditor_ShowAdvancedPasteTools"; + private const string SHOW_CLIPBOARD_INFORMATIONS_KEY = "TransformEditor_ShowClipboardInformations"; + private const string SHOW_SHORTCUTS_KEY = "TransformEditor_ShowHelpbox"; + + +#if UNITY_2017_3_OR_NEWER + private static System.Reflection.MethodInfo getLocalizedStringMethod; +#endif + + + /// Get translated Transform label + private static string LocalString(string text) + { +#if UNITY_2017_3_OR_NEWER + // Since Unity 2017.3, static class LocalizationDatabase is no longer public. Need to use reflection to access it. + if (getLocalizedStringMethod == null) + { + System.Reflection.Assembly assembly = typeof(UnityEditor.EditorWindow).Assembly; + System.Type localizationDatabaseType = assembly.GetType("UnityEditor.LocalizationDatabase"); + + getLocalizedStringMethod = localizationDatabaseType.GetMethod("GetLocalizedString"); + } + + return (string)getLocalizedStringMethod.Invoke(null, new object[] { text }); +#else + return LocalizationDatabase.GetLocalizedString(text); +#endif + } + + public void OnEnable() + { + positionProperty = serializedObject.FindProperty("m_LocalPosition"); + rotationProperty = serializedObject.FindProperty("m_LocalRotation"); + scaleProperty = serializedObject.FindProperty("m_LocalScale"); + + // Init options + if (!EditorPrefs.HasKey(SHOW_TOOLS_KEY)) EditorPrefs.SetBool(SHOW_TOOLS_KEY, true); + if (!EditorPrefs.HasKey(SHOW_RESET_TOOLS_KEY)) EditorPrefs.SetBool(SHOW_RESET_TOOLS_KEY, true); + if (!EditorPrefs.HasKey(SHOW_PASTE_TOOLS_KEY)) EditorPrefs.SetBool(SHOW_PASTE_TOOLS_KEY, true); + if (!EditorPrefs.HasKey(SHOW_ADVANCED_PASTE_TOOLS_KEY)) EditorPrefs.SetBool(SHOW_ADVANCED_PASTE_TOOLS_KEY, true); + if (!EditorPrefs.HasKey(SHOW_CLIPBOARD_INFORMATIONS_KEY)) EditorPrefs.SetBool(SHOW_CLIPBOARD_INFORMATIONS_KEY, true); + if (!EditorPrefs.HasKey(SHOW_SHORTCUTS_KEY)) EditorPrefs.SetBool(SHOW_SHORTCUTS_KEY, true); + } + + + public override void OnInspectorGUI() + { + Rect beginRect = GUILayoutUtility.GetRect(0, 0); + + EditorGUIUtility.wideMode = TransformEditor.WIDE_MODE; + EditorGUIUtility.labelWidth = EditorGUIUtility.currentViewWidth - TransformEditor.FIELD_WIDTH; // align field to right of inspector + + serializedObject.Update(); + + EditorGUIUtility.labelWidth = 60; // To allow float fields to expand when inspector width is increased + + // Position GUI + EditorGUILayout.BeginHorizontal(); + PositionPropertyField(positionProperty, positionGUIContent); // Note : Can't add generic menu if we use EditorGUILayout.PropertyField instead + if (EditorPrefs.GetBool(SHOW_TOOLS_KEY) && EditorPrefs.GetBool(SHOW_RESET_TOOLS_KEY)) + { + if (GUILayout.Button("Reset", GUILayout.Width(50))) + { + Undo.RecordObjects(targets, "Reset Positions"); + for (int i = 0; i < targets.Length; i++) + { + ((Transform)targets[i]).localPosition = Vector3.zero; + } + GUI.FocusControl(null); + } + } + EditorGUILayout.EndHorizontal(); + + // Rotation GUI + EditorGUILayout.BeginHorizontal(); + RotationPropertyField(rotationProperty, rotationGUIContent); // Note : Can't add generic menu if we use EditorGUILayout.PropertyField instead + if (EditorPrefs.GetBool(SHOW_TOOLS_KEY) && EditorPrefs.GetBool(SHOW_RESET_TOOLS_KEY)) + { + if (GUILayout.Button("Reset", GUILayout.Width(50))) + { + Undo.RecordObjects(targets, "Reset Rotations"); + for (int i = 0; i < targets.Length; i++) + { + TransformUtils.SetInspectorRotation(((Transform)targets[i]), Vector3.zero); + } + GUI.FocusControl(null); + } + + } + EditorGUILayout.EndHorizontal(); + + // Scale GUI + EditorGUILayout.BeginHorizontal(); + ScalePropertyField(scaleProperty, scaleGUIContent); // Note : Can't add generic menu if we use EditorGUILayout.PropertyField instead + if (EditorPrefs.GetBool(SHOW_TOOLS_KEY) && EditorPrefs.GetBool(SHOW_RESET_TOOLS_KEY)) + { + if (GUILayout.Button("Reset", GUILayout.Width(50))) + { + Undo.RecordObjects(targets, "Reset Scales"); + for (int i = 0; i < targets.Length; i++) + { + ((Transform)targets[i]).localScale = Vector3.one; + } + GUI.FocusControl(null); + } + } + EditorGUILayout.EndHorizontal(); + + + if (!ValidatePosition(((Transform)target).position)) EditorGUILayout.HelpBox(positionWarningText, MessageType.Warning); // Display floating-point warning message if values are too high + + if (EditorPrefs.GetBool(SHOW_TOOLS_KEY)) + { + // Paste Tools GUI + if (EditorPrefs.GetBool(SHOW_PASTE_TOOLS_KEY)) + { + GUILayout.BeginHorizontal(); + if (GUILayout.Button("Copy")) + { + positionClipboard = ((Transform)target).localPosition; + rotationClipboard = ((Transform)target).localRotation; + scaleClipboard = ((Transform)target).localScale; + } + + if (!positionClipboard.HasValue) EditorGUI.BeginDisabledGroup(true); + if (GUILayout.Button("Paste")) + { + Undo.RecordObjects(targets, "Paste Clipboard Values"); + for (int i = 0; i < targets.Length; i++) + { + ((Transform)targets[i]).localPosition = positionClipboard.Value; + ((Transform)targets[i]).localRotation = rotationClipboard.Value; + ((Transform)targets[i]).localScale = scaleClipboard.Value; + } + GUI.FocusControl(null); + } + if (!positionClipboard.HasValue) EditorGUI.EndDisabledGroup(); + GUILayout.EndHorizontal(); + } + + // Advanced Paste Tools GUI + if (EditorPrefs.GetBool(SHOW_ADVANCED_PASTE_TOOLS_KEY)) + { + GUILayout.BeginHorizontal(); + + if (!positionClipboard.HasValue) EditorGUI.BeginDisabledGroup(true); + if (GUILayout.Button("Paste position")) + { + Undo.RecordObjects(targets, "Paste Position Clipboard Value"); + for (int i = 0; i < targets.Length; i++) + { + ((Transform)targets[i]).localPosition = positionClipboard.Value; + } + GUI.FocusControl(null); + } + + if (GUILayout.Button("Paste rotation")) + { + Undo.RecordObjects(targets, "Paste Rotation Clipboard Value"); + for (int i = 0; i < targets.Length; i++) + { + ((Transform)targets[i]).rotation = rotationClipboard.Value; + } + GUI.FocusControl(null); + } + + if (GUILayout.Button("Paste scale")) + { + Undo.RecordObjects(targets, "Paste Scale Clipboard Value"); + for (int i = 0; i < targets.Length; i++) + { + ((Transform)targets[i]).localScale = scaleClipboard.Value; + } + GUI.FocusControl(null); + } + if (!positionClipboard.HasValue) EditorGUI.EndDisabledGroup(); + + GUILayout.EndHorizontal(); + } + + // Clipboard GUI + if (EditorPrefs.GetBool(SHOW_CLIPBOARD_INFORMATIONS_KEY)) + { + if (positionClipboard.HasValue && rotationClipboard.HasValue && scaleClipboard.HasValue) + { + + GUIStyle helpboxStyle = new GUIStyle(EditorStyles.helpBox); + helpboxStyle.richText = true; + + EditorGUILayout.TextArea("Clipboard values :\n" + + "Position : " + positionClipboard.Value.ToString("f2") + "\n" + + "Rotation : " + rotationClipboard.Value.ToString("f2") + "\n" + + "Scale : " + scaleClipboard.Value.ToString("f2"), helpboxStyle); + } + } + + + // Shortcuts GUI - Related to InspectorShortcuts.cs https://github.com/VoxelBoy/Useful-Unity-Scripts/blob/master/InspectorShortcuts.cs + if (EditorPrefs.GetBool(SHOW_SHORTCUTS_KEY)) + { + EditorGUILayout.HelpBox("Inspector shortcuts :\n" + + "Toggle inspector lock : Ctrl + Shift + L\n" + + "Toggle inspector mode : Ctrl + Shift + D", MessageType.None); + } + } + Rect endRect = GUILayoutUtility.GetLastRect(); + endRect.y += endRect.height; + + + #region Context Menu + Rect componentRect = new Rect(beginRect.x, beginRect.y, beginRect.width, endRect.y - beginRect.y); + //EditorGUI.DrawRect(componentRect, Color.green); // Debug : display GenericMenu zone + + Event currentEvent = Event.current; + + if (currentEvent.type == EventType.ContextClick) + { + if (componentRect.Contains(currentEvent.mousePosition)) + { + GUI.FocusControl(null); + + GenericMenu menu = new GenericMenu(); + + menu.AddItem(new GUIContent("Display/Tools"), EditorPrefs.GetBool(SHOW_TOOLS_KEY), ToggleOption, SHOW_TOOLS_KEY); + menu.AddSeparator("Display/"); + menu.AddItem(new GUIContent("Display/Reset Tools"), EditorPrefs.GetBool(SHOW_RESET_TOOLS_KEY), ToggleOption, SHOW_RESET_TOOLS_KEY); + menu.AddItem(new GUIContent("Display/Paste Tools"), EditorPrefs.GetBool(SHOW_PASTE_TOOLS_KEY), ToggleOption, SHOW_PASTE_TOOLS_KEY); + menu.AddItem(new GUIContent("Display/Advanced Paste Tools"), EditorPrefs.GetBool(SHOW_ADVANCED_PASTE_TOOLS_KEY), ToggleOption, SHOW_ADVANCED_PASTE_TOOLS_KEY); + menu.AddItem(new GUIContent("Display/Clipboard informations"), EditorPrefs.GetBool(SHOW_CLIPBOARD_INFORMATIONS_KEY), ToggleOption, SHOW_CLIPBOARD_INFORMATIONS_KEY); + menu.AddItem(new GUIContent("Display/Shortcuts informations"), EditorPrefs.GetBool(SHOW_SHORTCUTS_KEY), ToggleOption, SHOW_SHORTCUTS_KEY); + + // Round menu + menu.AddItem(new GUIContent("Round/Three Decimals"), false, Round, 3); + menu.AddItem(new GUIContent("Round/Two Decimals"), false, Round, 2); + menu.AddItem(new GUIContent("Round/One Decimal"), false, Round, 1); + menu.AddItem(new GUIContent("Round/Integer"), false, Round, 0); + + // Truncate menu + menu.AddItem(new GUIContent("Truncate/Three Decimals"), false, Truncate, 3); + menu.AddItem(new GUIContent("Truncate/Two Decimals"), false, Truncate, 2); + menu.AddItem(new GUIContent("Truncate/One Decimal"), false, Truncate, 1); + menu.AddItem(new GUIContent("Truncate/Integer"), false, Truncate, 0); + + menu.ShowAsContext(); + currentEvent.Use(); + } + } + #endregion + + serializedObject.ApplyModifiedProperties(); + } + + + private bool ValidatePosition(Vector3 position) + { + if (Mathf.Abs(position.x) > POSITION_MAX) return false; + if (Mathf.Abs(position.y) > POSITION_MAX) return false; + if (Mathf.Abs(position.z) > POSITION_MAX) return false; + return true; + } + + private void PositionPropertyField(SerializedProperty positionProperty, GUIContent content) + { + Transform transform = (Transform)targets[0]; + Vector3 localPosition = transform.localPosition; + for (int i = 0; i < targets.Length; i++) + { + if (!localPosition.Equals(((Transform)targets[i]).localPosition)) + { + EditorGUI.showMixedValue = true; + break; + } + } + + EditorGUI.BeginChangeCheck(); + Vector3 newLocalPosition = EditorGUILayout.Vector3Field(content, localPosition); + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObjects(targets, "Position Changed"); + for (int i = 0; i < targets.Length; i++) + { + ((Transform)targets[i]).localPosition = newLocalPosition; + } + positionProperty.serializedObject.SetIsDifferentCacheDirty(); + } + EditorGUI.showMixedValue = false; + } + + private void RotationPropertyField(SerializedProperty rotationProperty, GUIContent content) + { + Transform transform = (Transform)targets[0]; + Vector3 localRotation = TransformUtils.GetInspectorRotation(transform); + + + for (int i = 0; i < targets.Length; i++) + { + if (!localRotation.Equals(TransformUtils.GetInspectorRotation((Transform)targets[i]))) + { + EditorGUI.showMixedValue = true; + break; + } + } + + EditorGUI.BeginChangeCheck(); + Vector3 eulerAngles = EditorGUILayout.Vector3Field(content, localRotation); + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObjects(targets, "Rotation Changed"); + for (int i = 0; i < targets.Length; i++) + { + //((Transform)targets[i]).localEulerAngles = eulerAngles; + TransformUtils.SetInspectorRotation(((Transform)targets[i]), eulerAngles); + } + rotationProperty.serializedObject.SetIsDifferentCacheDirty(); + } + EditorGUI.showMixedValue = false; + } + + private void ScalePropertyField(SerializedProperty scaleProperty, GUIContent content) + { + Transform transform = (Transform)targets[0]; + Vector3 localScale = transform.localScale; + for (int i = 0; i < targets.Length; i++) + { + if (!localScale.Equals(((Transform)targets[i]).localScale)) + { + EditorGUI.showMixedValue = true; + break; + } + } + + EditorGUI.BeginChangeCheck(); + Vector3 newLocalScale = EditorGUILayout.Vector3Field(content, localScale); + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObjects(targets, "Scale Changed"); + for (int i = 0; i < targets.Length; i++) + { + ((Transform)targets[i]).localScale = newLocalScale; + } + scaleProperty.serializedObject.SetIsDifferentCacheDirty(); + } + EditorGUI.showMixedValue = false; + } + + + #region Generic Menu Callbacks + private void ToggleOption(object obj) + { + EditorPrefs.SetBool(obj.ToString(), !EditorPrefs.GetBool(obj.ToString())); + } + + /// Round all values of the Transform to a given number of decimals + private void Round(object objNumberOfDecimals) + { + int numberOfDecimals = (int)objNumberOfDecimals; + + Undo.RecordObjects(targets, "Round to " + numberOfDecimals + " decimals"); + for (int i = 0; i < targets.Length; i++) + { + ((Transform)targets[i]).localPosition = RoundVector(((Transform)targets[i]).localPosition, numberOfDecimals); + ((Transform)targets[i]).localEulerAngles = RoundVector(((Transform)targets[i]).localEulerAngles, numberOfDecimals); + ((Transform)targets[i]).localScale = RoundVector(((Transform)targets[i]).localScale, numberOfDecimals); + } + } + + /// Round all components of a Vector3 + private Vector3 RoundVector(Vector3 vector, int numberOfDecimals) + { + vector.x = Mathf.Round(vector.x * Mathf.Pow(10.0f, (float)numberOfDecimals)) / Mathf.Pow(10.0f, (float)numberOfDecimals); + vector.y = Mathf.Round(vector.y * Mathf.Pow(10.0f, (float)numberOfDecimals)) / Mathf.Pow(10.0f, (float)numberOfDecimals); + vector.z = Mathf.Round(vector.z * Mathf.Pow(10.0f, (float)numberOfDecimals)) / Mathf.Pow(10.0f, (float)numberOfDecimals); + return vector; + } + + /// Truncate all values of the Transform to a given number of decimals + private void Truncate(object objNumberOfDecimals) + { + int numberOfDecimals = (int)objNumberOfDecimals; + + Undo.RecordObjects(targets, "Truncate to " + numberOfDecimals + " decimals"); + for (int i = 0; i < targets.Length; i++) + { + ((Transform)targets[i]).localPosition = TruncateVector(((Transform)targets[i]).localPosition, numberOfDecimals); + ((Transform)targets[i]).localEulerAngles = TruncateVector(((Transform)targets[i]).localEulerAngles, numberOfDecimals); + ((Transform)targets[i]).localScale = TruncateVector(((Transform)targets[i]).localScale, numberOfDecimals); + } + } + + /// Truncate all components of a Vector3 + private Vector3 TruncateVector(Vector3 vector, int numberOfDecimals) + { + vector.x = Mathf.Floor(vector.x * Mathf.Pow(10.0f, (float)numberOfDecimals)) / Mathf.Pow(10.0f, (float)numberOfDecimals); + vector.y = Mathf.Floor(vector.y * Mathf.Pow(10.0f, (float)numberOfDecimals)) / Mathf.Pow(10.0f, (float)numberOfDecimals); + vector.z = Mathf.Floor(vector.z * Mathf.Pow(10.0f, (float)numberOfDecimals)) / Mathf.Pow(10.0f, (float)numberOfDecimals); + return vector; + } + #endregion + } +} diff --git a/Assets/Scripts/Editor/Debug/PropertyWatcher.cs b/Assets/Scripts/Editor/Debug/PropertyWatcher.cs new file mode 100644 index 0000000..451ceae --- /dev/null +++ b/Assets/Scripts/Editor/Debug/PropertyWatcher.cs @@ -0,0 +1,587 @@ +// Property Watcher - "who changed this?" for Inspector properties. +// Put this file in any Editor folder (Unity 2022.1 or newer). +// +// 1. Right-click a property in the Inspector > Watch Changes. +// 2. Enter Play mode. Window > Analysis > Property Watcher lists every change and its source. +// +// The value is compared at checkpoints in the player loop, so every change is caught and pinned +// to a loop stage (scripts, physics, animation...). +// If 0Harmony.dll (Harmony 2.2 or newer, the net48 build from the Harmony-Fat zip, set to Editor only) is in the project, +// download dll https://github.com/pardeike/Harmony/releases (copy to Assets/Plugins/PropertyWatcher or so) +// the code that can write the value is hooked as well, and the entry names the calling script with a call stack +// (click a row for the stack, double-click to open the file): +// - built-in components: the component's own void methods, e.g. Transform.set_position +// - script fields: every method whose IL writes the field + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading; +using UnityEditor; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.LowLevel; +using UnityEngine.SceneManagement; +using Debug = UnityEngine.Debug; +using Object = UnityEngine.Object; + +public class PropertyWatcher : EditorWindow +{ + const int MaxHistory = 30; + const string HarmonyId = "PropertyWatcher"; + const BindingFlags Declared = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + + [Serializable] + class Watch + { + public Object target; // serialized by the window, survives domain reloads + public string path; + [NonSerialized] public SerializedObject so; + [NonSerialized] public uint hash; + [NonSerialized] public string label, value; + [NonSerialized] public bool hooked, byInstance; + [NonSerialized] public List history; + } + + class Entry + { + public string time, source, from, to, stack, file; + public int line, count = 1; + } + + [Serializable] class Ref { public Object obj; } + + struct Checkpoint { } // marks our systems in the player loop + + [SerializeField] List watches = new List(); + [SerializeField] bool pauseOnChange; + Vector2 scroll; + Entry selected; + + static PropertyWatcher instance; + static int mainThread; + static bool busy, armed; + + // ---------------------------------------------------------------- setup + + [InitializeOnLoadMethod] + static void Init() + { + EditorApplication.contextualPropertyMenu += OnPropertyMenu; + EditorApplication.playModeStateChanged += OnPlayModeChanged; + SceneManager.sceneLoaded += (scene, mode) => Rebind(); + } + + [MenuItem("Window/Analysis/Property Watcher")] + static void Open() => GetWindow("Property Watcher"); + + void OnEnable() + { + instance = this; + mainThread = Thread.CurrentThread.ManagedThreadId; + // After the domain reload that starts Play mode this runs before any game code, so the hooks + // are in place before the game's methods get JIT-compiled (the JIT can inline small setters). + if (EditorApplication.isPlayingOrWillChangePlaymode) { Arm(); return; } + watches.RemoveAll(w => !w.target); // e.g. left over from a closed scene + Rebind(); + } + + void OnDisable() + { + Disarm(); + instance = null; + } + + static void OnPropertyMenu(GenericMenu menu, SerializedProperty property) + { + var targets = property.serializedObject.targetObjects; + string path = property.propertyPath; + bool watched = instance && instance.watches.Any(w => w.target == targets[0] && w.path == path); + + menu.AddItem(new GUIContent(watched ? "Stop Watching Changes" : "Watch Changes"), false, () => + { + var window = GetWindow("Property Watcher"); + foreach (var t in targets) + { + foreach (var old in window.watches.Where(w => w.target == t && w.path == path).ToArray()) Remove(old); + if (watched) continue; + var watch = new Watch { target = t, path = path }; + window.watches.Add(watch); + Bind(watch); + } + }); + } + + static void OnPlayModeChanged(PlayModeStateChange state) + { + if (!instance) return; + if (state == PlayModeStateChange.ExitingEditMode) + foreach (var w in instance.watches) w.history?.Clear(); + else if (state == PlayModeStateChange.EnteredPlayMode) Arm(); + else if (state == PlayModeStateChange.ExitingPlayMode) Disarm(); + else if (state == PlayModeStateChange.EnteredEditMode) Rebind(); // history stays readable + } + + static void Arm() + { + armed = true; + SetCheckpoints(true); + Rebind(); + } + + static void Disarm() + { + armed = false; + SetCheckpoints(false); + Unhook(); + if (instance) foreach (var w in instance.watches) w.hooked = false; + } + + static void Rebind() + { + if (instance) foreach (var w in instance.watches) Bind(w); + } + + static void Bind(Watch w) + { + w.history ??= new List(); + w.target = Refresh(w.target); + w.so = w.target ? new SerializedObject(w.target) : null; + if (w.so == null) return; + + var p = w.so.FindProperty(w.path); + string component = ObjectNames.NicifyVariableName(w.target.GetType().Name); + w.label = w.target.name + " > " + component + " > " + (p != null ? p.displayName : w.path); + if (p != null) { w.hash = p.contentHash; w.value = Format(p); } + + if (armed && !w.hooked) { w.hooked = true; Hook(w); } + } + + // Entering and exiting Play mode reloads the scene: the C# wrapper can go stale while the + // instance ID lives on. A JSON round trip resolves the reference again by ID. + static Object Refresh(Object obj) + { + var r = new Ref { obj = obj }; + JsonUtility.FromJsonOverwrite(JsonUtility.ToJson(r), r); + return r.obj ? r.obj : obj; + } + + static void Remove(Watch w) + { + if (instance) instance.watches.Remove(w); + foreach (var list in hooks.Values) list.Remove(w); + } + + // ---------------------------------------------------------------- change detection + + static readonly string[] Stages = { "Script", "Physics", "Director", "Animation", "AI", "Constraint", "Particle", "Cloth" }; + + // Adds (or strips) a value check after every interesting player-loop system and at the end of each phase. + static void SetCheckpoints(bool install) + { + var loop = PlayerLoop.GetCurrentPlayerLoop(); + var phases = loop.subSystemList; + if (phases == null) return; + + for (int i = 0; i < phases.Length; i++) + { + string phase = phases[i].type?.Name; + var list = new List(); + if (install && i == 0) list.Add(MakeCheckpoint("Editor: Inspector or editor code, between frames")); + + foreach (var system in phases[i].subSystemList ?? new PlayerLoopSystem[0]) + { + if (system.type == typeof(Checkpoint)) continue; + list.Add(system); + string name = system.type?.Name ?? ""; + if (install && Stages.Any(k => name.Contains(k))) + list.Add(MakeCheckpoint((name.Contains("Script") ? "Scripts: " : "Engine: ") + phase + "." + name)); + } + + if (install && (list.Count == 0 || list[list.Count - 1].type != typeof(Checkpoint))) + list.Add(MakeCheckpoint("Other: " + phase)); + phases[i].subSystemList = list.ToArray(); + } + PlayerLoop.SetPlayerLoop(loop); + } + + static PlayerLoopSystem MakeCheckpoint(string label) => new PlayerLoopSystem + { + type = typeof(Checkpoint), + updateDelegate = () => + { + if (instance) foreach (var w in instance.watches) Check(w, null, false, label); + } + }; + + // via == null: player-loop checkpoint. Otherwise called right before / after a hooked method. + // Runs inside game code when hooked, so it must never throw. + static void Check(Watch w, MethodBase via, bool after, string label) + { + if (busy || w.so == null || !w.target) return; + busy = true; // so.Update() can run user serialization callbacks + try + { + w.so.Update(); + var p = w.so.FindProperty(w.path); + if (p == null || p.contentHash == w.hash) return; + + var e = via == null ? new Entry { source = label } + : after ? Describe(via) + : new Entry { source = "Unknown (changed before " + Pretty(via) + " ran)" }; + e.time = DateTime.Now.ToString("HH:mm:ss") + " #" + Time.frameCount; + e.from = w.value; + e.to = w.value = Format(p); + w.hash = p.contentHash; + + var last = w.history.Count > 0 ? w.history[0] : null; + if (last != null && last.source == e.source && last.line == e.line) + { + last.count++; // same source again: update the row instead of adding one + last.time = e.time; last.from = e.from; last.to = e.to; last.stack = e.stack; + } + else + { + w.history.Insert(0, e); + if (w.history.Count > MaxHistory) w.history.RemoveAt(MaxHistory); + } + + if (instance && instance.pauseOnChange) Debug.Break(); + } + catch (Exception) { } // e.g. target destroyed mid-frame + finally { busy = false; } + } + + static string Format(SerializedProperty p) + { + try + { + switch (p.propertyType) + { + case SerializedPropertyType.Quaternion: return Text(p.quaternionValue.eulerAngles); + case SerializedPropertyType.ObjectReference: return p.objectReferenceValue ? p.objectReferenceValue.name : "None"; + case SerializedPropertyType.Enum: return p.enumValueIndex >= 0 ? p.enumDisplayNames[p.enumValueIndex] : p.intValue.ToString(); + case SerializedPropertyType.Generic: return (p.isArray ? p.arraySize + " items" : p.type) + " #" + p.contentHash.ToString("X8"); + default: return Text(p.boxedValue); + } + } + catch { return "#" + p.contentHash.ToString("X8"); } + } + + static string Text(object v) => v is IFormattable f ? f.ToString("0.###", CultureInfo.InvariantCulture) : v?.ToString() ?? "null"; + + // ---------------------------------------------------------------- attribution (optional Harmony) + + static Type harmonyType = FindType("HarmonyLib.Harmony"); + static object harmony, prefix, postfix; + static MethodInfo patchMethod, originalOf; + static readonly Dictionary> hooks = new Dictionary>(); // by method handle + static readonly string[] NotUser = { "UnityEngine", "UnityEditor", "Unity.Mathematics", "System", "mscorlib", "netstandard", "Mono.", "0Harmony", "MonoMod" }; + + static Type FindType(string name) => AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(name)).FirstOrDefault(t => t != null); + + static bool IsUserCode(Type t) + { + string assembly = t.Assembly.GetName().Name; + return !NotUser.Any(n => assembly.StartsWith(n)); + } + + // Harmony is used through reflection so the tool compiles with or without the DLL. + static bool InitHarmony() + { + if (harmony != null) return true; + if (harmonyType == null) return false; + try + { + const BindingFlags flags = BindingFlags.Static | BindingFlags.NonPublic; + var wrap = harmonyType.Assembly.GetType("HarmonyLib.HarmonyMethod").GetConstructor(new[] { typeof(MethodInfo) }); + prefix = wrap.Invoke(new object[] { typeof(PropertyWatcher).GetMethod(nameof(Pre), flags) }); + postfix = wrap.Invoke(new object[] { typeof(PropertyWatcher).GetMethod(nameof(Post), flags) }); + patchMethod = harmonyType.GetMethods().First(m => m.Name == "Patch" && m.GetParameters().Length >= 3); + originalOf = harmonyType.GetMethod("GetOriginalMethodFromStackframe", new[] { typeof(StackFrame) }); + harmony = Activator.CreateInstance(harmonyType, HarmonyId); + return true; + } + catch (Exception e) + { + Debug.LogWarning("Property Watcher: Harmony was found but could not be set up: " + e.Message); + harmonyType = null; + return false; + } + } + + static void Hook(Watch w) + { + if (!InitHarmony()) return; + var field = FindUserField(w.target.GetType(), w.path); + w.byInstance = field == null; + + if (field != null) + { + // Script field: hook every method that writes it; any instance may be the one written. + foreach (var m in FindWriters(field)) Patch(m, w); + return; + } + + // Engine property: hook the component's own void methods (setters, Translate, SetParent...). + for (var t = w.target.GetType(); t != null && t != typeof(Component) && t != typeof(Object); t = t.BaseType) + { + if (IsUserCode(t)) continue; + foreach (var m in t.GetMethods(Declared)) + if (m.ReturnType == typeof(void) && !m.ContainsGenericParameters && !m.Name.StartsWith("Get") && IL(m) != null) + Patch(m, w); + } + } + + static void Patch(MethodBase m, Watch w) + { + if (!hooks.TryGetValue(m.MethodHandle.Value, out var list)) + { + try + { + var args = new object[patchMethod.GetParameters().Length]; // (original, prefix, postfix, transpiler, finalizer) + args[0] = m; args[1] = prefix; args[2] = postfix; + patchMethod.Invoke(harmony, args); + } + catch { return; } // not patchable, skip + hooks[m.MethodHandle.Value] = list = new List(); + } + if (!list.Contains(w)) list.Add(w); + } + + static void Unhook() + { + if (harmony != null && hooks.Count > 0) + { + var unpatch = harmonyType.GetMethod("UnpatchSelf", Type.EmptyTypes) ?? harmonyType.GetMethod("UnpatchAll", new[] { typeof(string) }); + unpatch?.Invoke(harmony, unpatch.GetParameters().Length == 0 ? null : new object[] { HarmonyId }); + } + hooks.Clear(); + } + + // Harmony injects these parameters by name. + static void Pre(object __instance, MethodBase __originalMethod) => OnHook(__instance, __originalMethod, false); + static void Post(object __instance, MethodBase __originalMethod) => OnHook(__instance, __originalMethod, true); + + static void OnHook(object target, MethodBase method, bool after) + { + if (busy || Thread.CurrentThread.ManagedThreadId != mainThread) return; + if (!hooks.TryGetValue(method.MethodHandle.Value, out var list)) return; + for (int i = 0; i < list.Count; i++) + { + var w = list[i]; + if (!w.byInstance || (target is Object o && o == w.target)) Check(w, method, after, null); + } + } + + // Builds the "who" text and call stack for a change that a hooked method just made. + static Entry Describe(MethodBase via) + { + var e = new Entry(); + var lines = new List(); + string who = null, first = null; + + foreach (var frame in new StackTrace(true).GetFrames() ?? new StackFrame[0]) + { + var m = FrameMethod(frame); + if (m == null || m.DeclaringType == null || m.DeclaringType == typeof(PropertyWatcher)) continue; + if (m.DeclaringType == via.DeclaringType && m.Name == via.Name) continue; // the hooked method itself + if (m.DeclaringType.Name.StartsWith("DynamicMethodDefinition")) continue; // unresolved Harmony frame + + string name = Pretty(m), file = frame.GetFileName(); + bool hasFile = !string.IsNullOrEmpty(file); + lines.Add(name + (hasFile ? " " + Path.GetFileName(file) + ":" + frame.GetFileLineNumber() : "")); + first ??= name; + + if (!IsUserCode(m.DeclaringType)) continue; + who ??= name; + if (e.file == null && hasFile) { e.file = file; e.line = frame.GetFileLineNumber(); } // hooked methods have no line info + } + + who ??= first; + string writer = Pretty(via); + e.source = !IsUserCode(via.DeclaringType) ? (who ?? "Unity") + " -> " + writer // script, then the engine setter it called + : who == null || who == writer ? writer + : writer + " <- " + who; // field writer, then its caller + e.stack = string.Join("\n", lines); + return e; + } + + // A hooked method shows up on the stack as Harmony's replacement; map it back to the original. + static MethodBase FrameMethod(StackFrame frame) + { + MethodBase m = null; + try { m = originalOf?.Invoke(null, new object[] { frame }) as MethodBase; } catch { } + return m ?? frame.GetMethod(); + } + + static string Pretty(MethodBase m) + { + var t = m.DeclaringType; + string name = m.Name; + while (t != null && t.IsNested && t.Name.StartsWith("<")) // lambda, coroutine, async + { + if (name == "MoveNext") name = t.Name; + t = t.DeclaringType; + } + int end = name.IndexOf('>'); + if (name.StartsWith("<") && end > 1) name = name.Substring(1, end - 1); + return (t != null ? t.Name + "." : "") + name; + } + + // Deepest field on the property path that is declared in project code (null for native properties). + static FieldInfo FindUserField(Type type, string path) + { + FieldInfo best = null; + foreach (string part in path.Replace(".Array.data[", "[").Split('.')) + { + int bracket = part.IndexOf('['); + string name = bracket < 0 ? part : part.Substring(0, bracket); + + FieldInfo field = null; + for (var t = type; t != null && field == null; t = t.BaseType) field = t.GetField(name, Declared); + if (field == null) break; + + if (IsUserCode(field.DeclaringType)) best = field; + type = field.FieldType; + if (bracket >= 0) type = type.IsArray ? type.GetElementType() : type.IsGenericType ? type.GetGenericArguments()[0] : type; + } + return best; + } + + static IEnumerable FindWriters(FieldInfo field) + { + var home = field.DeclaringType.Assembly; + string homeName = home.GetName().Name; + + // A private field can only be written by its own class (and the lambdas/coroutines nested in it). + IEnumerable types = field.IsPrivate + ? WithNested(field.DeclaringType) + : AppDomain.CurrentDomain.GetAssemblies() + .Where(a => !a.IsDynamic && (a == home || (!field.IsAssembly && a.GetReferencedAssemblies().Any(r => r.Name == homeName)))) + .SelectMany(SafeTypes); + + foreach (var t in types) + { + if (t.IsValueType) continue; // struct methods are left alone, they fall back to the loop stage + foreach (var m in t.GetMethods(Declared | BindingFlags.Static)) + if (!m.ContainsGenericParameters && Writes(m, field)) yield return m; + } + } + + static IEnumerable WithNested(Type t) => + new[] { t }.Concat(t.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic).SelectMany(WithNested)); + + static IEnumerable SafeTypes(Assembly a) + { + try { return a.GetTypes(); } + catch (ReflectionTypeLoadException e) { return e.Types.Where(t => t != null); } + } + + static byte[] IL(MethodBase m) + { + try { return m.GetMethodBody()?.GetILAsByteArray(); } + catch { return null; } + } + + // True if the method contains stfld / ldflda for the field (ldflda covers "field.x = ..." and ref use). + static bool Writes(MethodBase m, FieldInfo field) + { + var il = IL(m); + if (il == null) return false; + + for (int i = 0; i + 4 < il.Length; i++) + { + if (il[i] != 0x7D && il[i] != 0x7C) continue; // stfld, ldflda + int token = BitConverter.ToInt32(il, i + 1); + int table = token >> 24; + if (table != 0x04 && table != 0x0A) continue; // FieldDef, MemberRef + try + { + var f = m.Module.ResolveField(token); + if (f.Module == field.Module && f.MetadataToken == field.MetadataToken) return true; + } + catch { } // the bytes were not a field token + } + return false; + } + + // ---------------------------------------------------------------- window + + void OnInspectorUpdate() => Repaint(); + + void OnGUI() + { + using (new EditorGUILayout.HorizontalScope(EditorStyles.toolbar)) + { + pauseOnChange = GUILayout.Toggle(pauseOnChange, "Pause on change", EditorStyles.toolbarButton); + if (GUILayout.Button("Clear history", EditorStyles.toolbarButton)) + foreach (var w in watches) w.history?.Clear(); + GUILayout.FlexibleSpace(); + GUILayout.Label(harmonyType != null ? "Harmony: on" : "Harmony: not found", EditorStyles.miniLabel); + } + + if (harmonyType == null) + EditorGUILayout.HelpBox("Without Harmony only the player-loop stage of a change is known. Add 0Harmony.dll (Harmony 2.2+, net48 build) to the project to see the calling script.", MessageType.Info); + if (watches.Count == 0) + EditorGUILayout.HelpBox("Right-click a property in the Inspector and choose \"Watch Changes\".", MessageType.Info); + + scroll = EditorGUILayout.BeginScrollView(scroll); + foreach (var w in watches.ToArray()) DrawWatch(w); + EditorGUILayout.EndScrollView(); + } + + void DrawWatch(Watch w) + { + w.history ??= new List(); + using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) + { + using (new EditorGUILayout.HorizontalScope()) + { + if (GUILayout.Button(w.label ?? w.path, EditorStyles.boldLabel)) EditorGUIUtility.PingObject(w.target); + if (GUILayout.Button("Remove", EditorStyles.miniButton, GUILayout.Width(60))) Remove(w); + } + + if (!w.target || w.so == null) + { + EditorGUILayout.LabelField("Object is gone."); + return; + } + + if (!EditorApplication.isPlaying) // outside Play mode just mirror the Inspector + { + w.so.Update(); + var p = w.so.FindProperty(w.path); + if (p != null) w.value = Format(p); + } + + EditorGUILayout.LabelField("Current", w.value); + EditorGUILayout.LabelField("Last changed by", w.history.Count > 0 ? w.history[0].source : "-"); + + var ev = Event.current; + foreach (var e in w.history) + { + string row = e.time + " " + e.source + (e.count > 1 ? " x" + e.count : "") + " " + e.from + " -> " + e.to; + var style = e == selected ? EditorStyles.boldLabel : EditorStyles.label; + var rect = GUILayoutUtility.GetRect(new GUIContent(row), style); + + // click: show the stack, double-click: open the script + if (ev.type == EventType.MouseDown && rect.Contains(ev.mousePosition)) + { + selected = e; + if (ev.clickCount == 2 && !string.IsNullOrEmpty(e.file)) + InternalEditorUtility.OpenFileAtLineExternal(e.file, e.line); + ev.Use(); + } + GUI.Label(rect, row, style); + } + + if (selected != null && w.history.Contains(selected) && !string.IsNullOrEmpty(selected.stack)) + EditorGUILayout.HelpBox(selected.stack, MessageType.None); + } + } +} diff --git a/Assets/Scripts/Editor/Hierarchy/MoveAround.cs b/Assets/Scripts/Editor/Hierarchy/MoveAround.cs new file mode 100644 index 0000000..1ac886c --- /dev/null +++ b/Assets/Scripts/Editor/Hierarchy/MoveAround.cs @@ -0,0 +1,77 @@ +// Simple shortcuts for moving selected GameObject around in hierarchy by Factuall +// SHIFT + CTRL + ALT + +// W - Move it up in hierarchy +// S - Move it down in hierarchy +// A - Unparent it down +// D - Parent it to next object in hierarchy + +using UnityEditor; + +namespace UnityLibrary +{ + public class UnparentMe + { + [MenuItem("GameObject/Unparent %#&a")] + static void Detach() + { + + if (Selection.activeGameObject != null && Selection.activeGameObject.transform.parent != null) + { + int newIndex = Selection.activeGameObject.transform.parent.GetSiblingIndex(); + Undo.SetTransformParent(Selection.activeGameObject.transform, Selection.activeGameObject.transform.parent.parent, "unparent selection"); + Selection.activeGameObject.transform.SetSiblingIndex(newIndex + 1); + } + } + [MenuItem("GameObject/ParentDown %#&d")] + static void ParentDown() + { + if (Selection.activeGameObject != null) + { + int parentChildCount = Selection.activeGameObject.transform.parent == null ? + Selection.activeGameObject.scene.rootCount : Selection.activeGameObject.transform.parent.childCount; + if (Selection.activeGameObject.transform.GetSiblingIndex() == parentChildCount - 1) return; + if (Selection.activeGameObject.transform.parent != null) + { + if (Selection.activeGameObject.transform.parent.childCount + 1 > Selection.activeGameObject.transform.GetSiblingIndex()) + Undo.SetTransformParent(Selection.activeGameObject.transform, Selection.activeGameObject.transform.parent.GetChild(Selection.activeGameObject.transform.GetSiblingIndex() + 1), "parent selection down in hierarchy"); + + } + else + { + if (Selection.activeGameObject.scene.rootCount + 1 > Selection.activeGameObject.transform.GetSiblingIndex()) + Undo.SetTransformParent(Selection.activeGameObject.transform, Selection.activeGameObject.scene.GetRootGameObjects()[Selection.activeGameObject.transform.GetSiblingIndex() + 1].transform, "parent selection down in hierarchy"); + } + } + + } + [MenuItem("GameObject/Moveup %#&w")] + static void MoveUp() + { + if (Selection.activeGameObject != null) + { + + if (Selection.activeGameObject.transform.GetSiblingIndex() != 0) + { + Undo.RegisterCompleteObjectUndo(Selection.activeGameObject.transform, "move selction up in hierarchy"); + Selection.activeGameObject.transform.SetSiblingIndex(Selection.activeGameObject.transform.GetSiblingIndex() - 1); + } + + } + } + [MenuItem("GameObject/Movedown %#&s")] + static void MoveDown() + { + if (Selection.activeGameObject != null) + { + int parentChildCount = Selection.activeGameObject.transform.parent == null ? + Selection.activeGameObject.scene.rootCount : Selection.activeGameObject.transform.parent.childCount; + if (Selection.activeGameObject.transform.GetSiblingIndex() != parentChildCount - 1) + { + Undo.RegisterCompleteObjectUndo(Selection.activeGameObject.transform, "move selction down in hierarchy"); + Selection.activeGameObject.transform.SetSiblingIndex(Selection.activeGameObject.transform.GetSiblingIndex() + 1); + } + + } + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Editor/Hierarchy/MoveAround.cs.meta b/Assets/Scripts/Editor/Hierarchy/MoveAround.cs.meta new file mode 100644 index 0000000..41e518a --- /dev/null +++ b/Assets/Scripts/Editor/Hierarchy/MoveAround.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 18fe530f4fbd8b74096f07f377a4b9ff +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/Importers/AnimationClipListImporter.cs b/Assets/Scripts/Editor/Importers/AnimationClipListImporter.cs new file mode 100644 index 0000000..733ac03 --- /dev/null +++ b/Assets/Scripts/Editor/Importers/AnimationClipListImporter.cs @@ -0,0 +1,65 @@ +// Checks for a .txt file with the same name as an imported .fbx file (in Assets/Models/ folder), containing a list of animation clips to add to the ModelImporter. +// .txt file should be tab-delimited with the following columns: "title", "start frame", "end frame" (and optional description, not used). +// example: +// Take0 10 40 asdf +// Take1 50 80 wasdf.. + +using System; +using System.IO; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; + +namespace UnityLibrary.Importers +{ + public class AnimationClipListImporter : AssetPostprocessor + { + void OnPreprocessModel() + { + ModelImporter modelImporter = assetImporter as ModelImporter; + if (modelImporter == null) return; + + string assetPath = assetImporter.assetPath; + if (!assetPath.StartsWith("Assets/Models") || !assetPath.EndsWith(".fbx", StringComparison.OrdinalIgnoreCase)) return; + + string txtPath = Path.ChangeExtension(assetPath, ".txt"); + if (!File.Exists(txtPath)) return; + + try + { + List clips = new List(); + string[] lines = File.ReadAllLines(txtPath); + + foreach (string line in lines) + { + string[] parts = line.Split('\t'); + if (parts.Length < 3) continue; // Ensure we have at least "title, start, end" + + string title = parts[0].Trim(); + if (!int.TryParse(parts[1], out int startFrame) || !int.TryParse(parts[2], out int endFrame)) + continue; + + ModelImporterClipAnimation clip = new ModelImporterClipAnimation + { + name = title, + firstFrame = startFrame, + lastFrame = endFrame, + loopTime = false + }; + + clips.Add(clip); + } + + if (clips.Count > 0) + { + modelImporter.clipAnimations = clips.ToArray(); + Debug.Log($"Added {clips.Count} animation clips to {assetPath}"); + } + } + catch (Exception ex) + { + Debug.LogError($"Failed to process animation data for {assetPath}: {ex.Message}"); + } + } + } +} diff --git a/Assets/Scripts/Editor/Importers/MegaScansURPImporter.cs b/Assets/Scripts/Editor/Importers/MegaScansURPImporter.cs new file mode 100644 index 0000000..ce75453 --- /dev/null +++ b/Assets/Scripts/Editor/Importers/MegaScansURPImporter.cs @@ -0,0 +1,647 @@ +// MegaScansURPImporter.cs +// Place in Assets/Editor. Requires Unity 2022.3+ with URP (tested against Unity 6 APIs). +// Processes FBX + source textures under Assets/Models/MegaScans recursively. +// Generated outputs are written to each model's _URPGenerated directory. + +#if UNITY_EDITOR +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using UnityEditor; +using UnityEngine; +using UnityEngine.Rendering; + +namespace UnityLibrary.EditorTools +{ + public sealed class MegaScansURPImporterWindow : EditorWindow + { + internal const string Root = "Assets/Models/MegaScans"; + internal const string OutputFolder = "_URPGenerated"; + + private const string Prefix = "UnityLibrary.MegaScansURP."; + private const string AutoKey = Prefix + "Auto"; + private const string FlipKey = Prefix + "FlipGreen"; + private const string CutoffKey = Prefix + "Cutoff"; + private const string SmoothnessKey = Prefix + "Smoothness"; + private const string MaxSizeKey = Prefix + "MaxSize"; + + internal static bool AutoProcess { get { return EditorPrefs.GetBool(AutoKey, true); } } + internal static bool FlipUnknownNormals { get { return EditorPrefs.GetBool(FlipKey, false); } } + internal static float Cutoff { get { return EditorPrefs.GetFloat(CutoffKey, 0.5f); } } + internal static float DefaultSmoothness { get { return EditorPrefs.GetFloat(SmoothnessKey, 0.45f); } } + internal static int MaxPackedSize { get { return EditorPrefs.GetInt(MaxSizeKey, 4096); } } + + [MenuItem("Tools/MegaScans URP/Importer Settings")] + private static void OpenWindow() + { + GetWindow("MegaScans URP"); + } + + [MenuItem("Tools/MegaScans URP/Process All Models")] + private static void ProcessAllMenu() + { + MegaScansURPProcessor.ProcessAll(true); + } + + private void OnGUI() + { + EditorGUILayout.LabelField("Fab / Quixel MegaScans to URP Lit", EditorStyles.boldLabel); + EditorGUILayout.HelpBox("Only processes FBX models beneath " + Root + ". Output materials and generated PNGs are stored in each model folder's " + OutputFolder + " subfolder.", MessageType.Info); + EditorGUILayout.Space(); + + bool autoProcess = EditorGUILayout.Toggle(new GUIContent("Auto-process imports", "Run when a source FBX or texture is imported/changed."), AutoProcess); + bool flip = EditorGUILayout.Toggle(new GUIContent("Flip ambiguous normal green", "Enable for DirectX-format files named simply Normal. NormalDX and NormalGL are detected automatically."), FlipUnknownNormals); + float cutoff = EditorGUILayout.Slider(new GUIContent("Opacity alpha cutoff"), Cutoff, 0.01f, 0.99f); + float smoothness = EditorGUILayout.Slider(new GUIContent("Fallback smoothness"), DefaultSmoothness, 0f, 1f); + int size = EditorGUILayout.IntPopup( + new GUIContent("Maximum packed size"), + MaxPackedSize, + new[] { new GUIContent("1024"), new GUIContent("2048"), new GUIContent("4096"), new GUIContent("8192") }, + new[] { 1024, 2048, 4096, 8192 }); + + bool changed = autoProcess != AutoProcess || flip != FlipUnknownNormals || !Mathf.Approximately(cutoff, Cutoff) || !Mathf.Approximately(smoothness, DefaultSmoothness) || size != MaxPackedSize; + if (changed) + { + EditorPrefs.SetBool(AutoKey, autoProcess); + EditorPrefs.SetBool(FlipKey, flip); + EditorPrefs.SetFloat(CutoffKey, cutoff); + EditorPrefs.SetFloat(SmoothnessKey, smoothness); + EditorPrefs.SetInt(MaxSizeKey, size); + } + + EditorGUILayout.Space(); + if (GUILayout.Button("Process All MegaScans FBX Models", GUILayout.Height(34))) MegaScansURPProcessor.ProcessAll(true); + EditorGUILayout.HelpBox("Supported: BaseColor/Albedo, Normal/NormalDX/NormalGL, Roughness, AO, Metallic/Metalness, Opacity, and ORM/ARM/RMA/ORD packed maps. JPG and PNG are supported as channel-packing input. Other Unity-importable texture formats work for BaseColor and Normal.", MessageType.None); + EditorGUILayout.HelpBox("The processor assumes one texture set per FBX. If a model contains several different material surfaces, its FBX material slots will all point to the same generated material.", MessageType.Warning); + } + } + + internal static class MegaScansURPProcessor + { + private sealed class TextureSource + { + internal string Path; + internal string Kind; + internal int Score; + } + + private sealed class TextureSet + { + internal string BaseColor; + internal string Normal; + internal string Roughness; + internal string AO; + internal string Metalness; + internal string Opacity; + internal string Packed; + internal string PackedKind; + } + + private sealed class ImageData + { + internal int Width; + internal int Height; + internal Color32[] Pixels; + internal byte Sample(float u, float v, int channel) + { + if (Pixels == null || Pixels.Length == 0) return 255; + int x = Mathf.Clamp(Mathf.RoundToInt(u * (Width - 1)), 0, Width - 1); + int y = Mathf.Clamp(Mathf.RoundToInt(v * (Height - 1)), 0, Height - 1); + Color32 c = Pixels[y * Width + x]; + if (channel == 0) return c.r; + if (channel == 1) return c.g; + if (channel == 2) return c.b; + return c.a; + } + } + + private static readonly HashSet TextureExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) { ".jpg", ".jpeg", ".png", ".tga", ".tif", ".tiff", ".psd", ".exr" }; + private static readonly HashSet PendingModels = new HashSet(StringComparer.OrdinalIgnoreCase); + private static bool processing; + private static bool pendingScheduled; + + internal static bool IsInsideRoot(string assetPath) + { + return !string.IsNullOrEmpty(assetPath) && assetPath.StartsWith(MegaScansURPImporterWindow.Root + "/", StringComparison.OrdinalIgnoreCase) && assetPath.IndexOf("/" + MegaScansURPImporterWindow.OutputFolder + "/", StringComparison.OrdinalIgnoreCase) < 0; + } + + internal static bool IsSourceTexture(string path) + { + return IsInsideRoot(path) && TextureExtensions.Contains(System.IO.Path.GetExtension(path)); + } + + internal static bool IsSourceModel(string path) + { + return IsInsideRoot(path) && path.EndsWith(".fbx", StringComparison.OrdinalIgnoreCase); + } + + internal static void EnqueueChangedAssets(IEnumerable paths) + { + if (!MegaScansURPImporterWindow.AutoProcess || processing) return; + bool any = false; + foreach (string path in paths) + { + if (IsSourceModel(path)) + { + any |= PendingModels.Add(path); + continue; + } + if (!IsSourceTexture(path)) continue; + string directory = System.IO.Path.GetDirectoryName(path).Replace('\\', '/'); + string parent = System.IO.Path.GetDirectoryName(directory).Replace('\\', '/'); + string folderName = System.IO.Path.GetFileName(directory); + bool usesTextureSubfolder = folderName.Equals("Textures", StringComparison.OrdinalIgnoreCase) || folderName.Equals("Texture", StringComparison.OrdinalIgnoreCase) || folderName.Equals("Maps", StringComparison.OrdinalIgnoreCase); + foreach (string folder in usesTextureSubfolder ? new[] { directory, parent } : new[] { directory }) + { + if (folder == null || !folder.StartsWith(MegaScansURPImporterWindow.Root, StringComparison.OrdinalIgnoreCase) || !AssetDatabase.IsValidFolder(folder)) continue; + foreach (string guid in AssetDatabase.FindAssets("t:Model", new[] { folder })) + { + string model = AssetDatabase.GUIDToAssetPath(guid); + if (IsSourceModel(model)) any |= PendingModels.Add(model); + } + } + } + if (!any || pendingScheduled) return; + pendingScheduled = true; + EditorApplication.delayCall += ProcessPending; + } + + private static void ProcessPending() + { + pendingScheduled = false; + if (processing || PendingModels.Count == 0) return; + List models = PendingModels.ToList(); + PendingModels.Clear(); + ProcessModels(models, false); + } + + internal static void ProcessAll(bool showProgress) + { + if (!AssetDatabase.IsValidFolder(MegaScansURPImporterWindow.Root)) + { + Debug.LogWarning("MegaScans URP: Folder not found: " + MegaScansURPImporterWindow.Root); + return; + } + List models = AssetDatabase.FindAssets("t:Model", new[] { MegaScansURPImporterWindow.Root }).Select(AssetDatabase.GUIDToAssetPath).Where(IsSourceModel).Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(x => x).ToList(); + ProcessModels(models, showProgress); + } + + private static void ProcessModels(IList models, bool showProgress) + { + if (processing) return; + Shader shader = Shader.Find("Universal Render Pipeline/Lit"); + if (shader == null) + { + Debug.LogError("MegaScans URP: Universal Render Pipeline/Lit shader not found. Install and configure URP first."); + return; + } + processing = true; + int succeeded = 0; + int skipped = 0; + int failed = 0; + try + { + for (int i = 0; i < models.Count; i++) + { + string model = models[i]; + if (showProgress && EditorUtility.DisplayCancelableProgressBar("Processing MegaScans", model, models.Count > 0 ? (float)i / models.Count : 1f)) break; + if (!IsSourceModel(model) || AssetDatabase.LoadAssetAtPath(model) == null) { skipped++; continue; } + try + { + if (ProcessModel(model, shader)) succeeded++; + else skipped++; + } + catch (Exception ex) + { + failed++; + Debug.LogError("MegaScans URP: Failed to process " + model + "\n" + ex); + } + } + AssetDatabase.SaveAssets(); + } + finally + { + if (showProgress) EditorUtility.ClearProgressBar(); + processing = false; + } + Debug.Log("MegaScans URP: Processed " + succeeded + " FBX models; skipped " + skipped + "; errors " + failed + "."); + } + + private static bool ProcessModel(string modelPath, Shader shader) + { + TextureSet set = DiscoverTextureSet(modelPath); + if (string.IsNullOrEmpty(set.BaseColor) && string.IsNullOrEmpty(set.Normal) && string.IsNullOrEmpty(set.Roughness) && string.IsNullOrEmpty(set.AO) && string.IsNullOrEmpty(set.Packed)) + { + Debug.LogWarning("MegaScans URP: No matching texture set for " + modelPath); + return false; + } + + string dir = System.IO.Path.GetDirectoryName(modelPath).Replace('\\', '/'); + string name = System.IO.Path.GetFileNameWithoutExtension(modelPath); + string outputDir = dir + "/" + MegaScansURPImporterWindow.OutputFolder; + if (!AssetDatabase.IsValidFolder(outputDir)) AssetDatabase.CreateFolder(dir, MegaScansURPImporterWindow.OutputFolder); + + string baseMapPath = set.BaseColor; + bool alphaClip = !string.IsNullOrEmpty(set.Opacity) && !string.IsNullOrEmpty(set.BaseColor); + if (alphaClip) + { + string generatedBase = outputDir + "/" + name + "_URP_BaseColor.png"; + if (GenerateBaseColorAlpha(set.BaseColor, set.Opacity, generatedBase)) baseMapPath = generatedBase; + else { alphaClip = false; Debug.LogWarning("MegaScans URP: Could not combine opacity map for " + modelPath); } + } + + Texture2D baseMap = LoadTexture(baseMapPath); + if (!string.IsNullOrEmpty(set.Normal)) ConfigureNormal(set.Normal); + Texture2D normal = LoadTexture(set.Normal); + + Texture2D packed = null; + bool hasPackedInputs = !string.IsNullOrEmpty(set.Roughness) || !string.IsNullOrEmpty(set.AO) || !string.IsNullOrEmpty(set.Metalness) || !string.IsNullOrEmpty(set.Packed); + if (hasPackedInputs) + { + string packedPath = outputDir + "/" + name + "_URP_Mask.png"; + if (GeneratePackedMask(set, packedPath)) + { + ConfigureDataTexture(packedPath); + packed = LoadTexture(packedPath); + } + } + + string materialPath = outputDir + "/" + name + "_URP.mat"; + Material material = AssetDatabase.LoadAssetAtPath(materialPath); + if (material == null) + { + material = new Material(shader); + AssetDatabase.CreateAsset(material, materialPath); + } + else if (material.shader != shader) material.shader = shader; + + material.SetFloat("_WorkflowMode", 1f); + material.SetFloat("_Surface", 0f); + material.SetFloat("_Blend", 0f); + material.SetFloat("_AlphaClip", alphaClip ? 1f : 0f); + material.SetFloat("_Cutoff", MegaScansURPImporterWindow.Cutoff); + material.SetFloat("_Cull", alphaClip ? 0f : 2f); + material.SetColor("_BaseColor", Color.white); + material.SetTexture("_BaseMap", baseMap); + material.SetTexture("_BumpMap", normal); + material.SetFloat("_BumpScale", 1f); + material.SetTexture("_MetallicGlossMap", packed); + material.SetTexture("_OcclusionMap", packed); + material.SetFloat("_Metallic", string.IsNullOrEmpty(set.Metalness) && string.IsNullOrEmpty(set.Packed) ? 0f : 1f); + material.SetFloat("_Smoothness", packed != null ? 1f : MegaScansURPImporterWindow.DefaultSmoothness); + material.SetFloat("_SmoothnessTextureChannel", 0f); + material.SetFloat("_OcclusionStrength", 1f); + SetKeyword(material, "_NORMALMAP", normal != null); + SetKeyword(material, "_METALLICSPECGLOSSMAP", packed != null); + SetKeyword(material, "_OCCLUSIONMAP", packed != null); + SetKeyword(material, "_ALPHATEST_ON", alphaClip); + SetKeyword(material, "_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A", false); + material.renderQueue = alphaClip ? (int)RenderQueue.AlphaTest : -1; + material.enableInstancing = true; + EditorUtility.SetDirty(material); + + RemapModelMaterials(modelPath, material); + return true; + } + + private static void RemapModelMaterials(string modelPath, Material material) + { + ModelImporter importer = AssetImporter.GetAtPath(modelPath) as ModelImporter; + if (importer == null) return; + bool changed = false; + if (importer.materialImportMode == ModelImporterMaterialImportMode.None) + { + importer.materialImportMode = ModelImporterMaterialImportMode.ImportStandard; + changed = true; + } + + HashSet names = new HashSet(StringComparer.Ordinal); + foreach (var pair in importer.GetExternalObjectMap()) + { + if (pair.Key.type == typeof(Material) && !string.IsNullOrEmpty(pair.Key.name)) names.Add(pair.Key.name); + } + GameObject prefab = AssetDatabase.LoadAssetAtPath(modelPath); + if (prefab != null) + { + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + foreach (Material m in renderer.sharedMaterials) + { + if (m != null && !string.IsNullOrEmpty(m.name)) names.Add(m.name); + } + } + } + foreach (Material m in AssetDatabase.LoadAllAssetsAtPath(modelPath).OfType()) + { + if (!string.IsNullOrEmpty(m.name)) names.Add(m.name); + } + if (names.Count == 0) + { + Debug.LogWarning("MegaScans URP: No material slots found in " + modelPath + ". You may need to enable Import Materials on this FBX and run the processor again."); + } + + var existingMap = importer.GetExternalObjectMap(); + foreach (string name in names) + { + var key = new AssetImporter.SourceAssetIdentifier(typeof(Material), name); + UnityEngine.Object existing; + if (existingMap.TryGetValue(key, out existing) && existing == material) continue; + importer.AddRemap(key, material); + changed = true; + } + if (!changed) return; + AssetDatabase.WriteImportSettingsIfDirty(modelPath); + AssetDatabase.ImportAsset(modelPath, ImportAssetOptions.ForceUpdate); + } + + private static TextureSet DiscoverTextureSet(string modelPath) + { + string directory = System.IO.Path.GetDirectoryName(modelPath).Replace('\\', '/'); + string filename = System.IO.Path.GetFileNameWithoutExtension(modelPath); + string normalized = StripLodSuffix(filename); + string id = ExtractMegascansId(filename); + List sources = new List(); + + foreach (string guid in AssetDatabase.FindAssets("t:Texture2D", new[] { directory })) + { + string path = AssetDatabase.GUIDToAssetPath(guid); + if (!IsSourceTexture(path)) continue; + string stem = System.IO.Path.GetFileNameWithoutExtension(path); + string kind = ClassifyTexture(stem); + if (kind == null) continue; + string textureDir = System.IO.Path.GetDirectoryName(path).Replace('\\', '/'); + bool sameFolder = string.Equals(textureDir, directory, StringComparison.OrdinalIgnoreCase); + bool fullMatch = stem.StartsWith(filename + "_", StringComparison.OrdinalIgnoreCase) || string.Equals(stem, filename, StringComparison.OrdinalIgnoreCase); + bool lodMatch = stem.StartsWith(normalized + "_", StringComparison.OrdinalIgnoreCase); + bool idMatch = id != null && stem.IndexOf(id, StringComparison.OrdinalIgnoreCase) >= 0; + if (!fullMatch && !lodMatch && !idMatch) continue; + int score = (fullMatch ? 1000 : lodMatch ? 800 : 500) + (sameFolder ? 100 : 0) + ResolutionScore(stem); + if (kind == "NormalGL") score += 30; + sources.Add(new TextureSource { Path = path, Kind = kind, Score = score }); + } + + // Some Fab downloads use generic texture names, but only fall back when + // there is exactly one FBX in that folder to avoid cross-asset mixing. + if (sources.Count == 0) + { + int fbxCount = AssetDatabase.FindAssets("t:Model", new[] { directory }).Select(AssetDatabase.GUIDToAssetPath).Count(p => IsSourceModel(p) && string.Equals(System.IO.Path.GetDirectoryName(p).Replace('\\', '/'), directory, StringComparison.OrdinalIgnoreCase)); + if (fbxCount == 1) + { + foreach (string guid in AssetDatabase.FindAssets("t:Texture2D", new[] { directory })) + { + string path = AssetDatabase.GUIDToAssetPath(guid); + if (!IsSourceTexture(path) || !string.Equals(System.IO.Path.GetDirectoryName(path).Replace('\\', '/'), directory, StringComparison.OrdinalIgnoreCase)) continue; + string stem = System.IO.Path.GetFileNameWithoutExtension(path); + string kind = ClassifyTexture(stem); + if (kind != null) sources.Add(new TextureSource { Path = path, Kind = kind, Score = ResolutionScore(stem) }); + } + } + } + + TextureSet result = new TextureSet(); + result.BaseColor = Best(sources, "BaseColor"); + result.Normal = Best(sources, "NormalGL") ?? Best(sources, "Normal") ?? Best(sources, "NormalDX"); + result.Roughness = Best(sources, "Roughness"); + result.AO = Best(sources, "AO"); + result.Metalness = Best(sources, "Metalness"); + result.Opacity = Best(sources, "Opacity"); + TextureSource packed = sources.Where(s => s.Kind == "ORM" || s.Kind == "ARM" || s.Kind == "RMA" || s.Kind == "ORD" || s.Kind == "MRA").OrderByDescending(s => s.Score).FirstOrDefault(); + if (packed != null) { result.Packed = packed.Path; result.PackedKind = packed.Kind; } + return result; + } + + private static string Best(List sources, string kind) + { + TextureSource source = sources.Where(s => s.Kind == kind).OrderByDescending(s => s.Score).FirstOrDefault(); + return source != null ? source.Path : null; + } + + private static string StripLodSuffix(string name) + { + return Regex.Replace(name, @"(?i)(?:[_-](?:low|high|mid|nanite|lod[0-9]+))+$", ""); + } + + private static string ExtractMegascansId(string name) + { + MatchCollection matches = Regex.Matches(name, @"(?i)(?:^|[_-])([a-z0-9]{7,9})(?=[_-]|$)"); + return matches.Count > 0 ? matches[matches.Count - 1].Groups[1].Value : null; + } + + private static int ResolutionScore(string name) + { + Match match = Regex.Match(name, @"(?i)(?:^|[_-])([0-9]{1,2})k(?:[_-]|$)"); + int value; + return match.Success && int.TryParse(match.Groups[1].Value, out value) ? value * 4 : 0; + } + + private static string ClassifyTexture(string stem) + { + string[] tokens = Regex.Split(stem.ToLowerInvariant(), @"[_\-. ]+"); + for (int i = tokens.Length - 1; i >= 0; i--) + { + string t = tokens[i]; + if (t == "basecolor" || t == "albedo" || t == "diffuse" || t == "diff" || t == "basecolour") return "BaseColor"; + if (t == "normalgl" || t == "normalogl" || t == "normalopengl") return "NormalGL"; + if (t == "normaldx" || t == "normaldirectx") return "NormalDX"; + if (t == "normal" || t == "normals" || t == "nrm") return i + 1 < tokens.Length && tokens[i + 1] == "dx" ? "NormalDX" : i + 1 < tokens.Length && (tokens[i + 1] == "gl" || tokens[i + 1] == "opengl") ? "NormalGL" : "Normal"; + if (t == "roughness" || t == "rough") return "Roughness"; + if (t == "ao" || t == "ambientocclusion" || t == "occlusion") return "AO"; + if (t == "metalness" || t == "metallic" || t == "metal") return "Metalness"; + if (t == "opacity" || t == "alpha" || t == "opacitymask" || t == "mask") return "Opacity"; + if (t == "orm") return "ORM"; + if (t == "arm") return "ARM"; + if (t == "rma" || t == "rmetal") return "RMA"; + if (t == "mra") return "MRA"; + if (t == "ord" || t == "ordp") return "ORD"; + } + return null; + } + + private static Texture2D LoadTexture(string path) + { + return !string.IsNullOrEmpty(path) ? AssetDatabase.LoadAssetAtPath(path) : null; + } + + private static void ConfigureNormal(string path) + { + TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter; + if (importer == null) return; + bool flip = path.IndexOf("normaldx", StringComparison.OrdinalIgnoreCase) >= 0 || (path.IndexOf("normalgl", StringComparison.OrdinalIgnoreCase) < 0 && MegaScansURPImporterWindow.FlipUnknownNormals); + if (importer.textureType == TextureImporterType.NormalMap && importer.flipGreenChannel == flip) return; + importer.textureType = TextureImporterType.NormalMap; + importer.flipGreenChannel = flip; + importer.SaveAndReimport(); + } + + private static void ConfigureDataTexture(string path) + { + TextureImporter importer = AssetImporter.GetAtPath(path) as TextureImporter; + if (importer == null) return; + if (importer.textureType == TextureImporterType.Default && !importer.sRGBTexture && importer.mipmapEnabled && !importer.isReadable) return; + importer.textureType = TextureImporterType.Default; + importer.sRGBTexture = false; + importer.mipmapEnabled = true; + importer.isReadable = false; + importer.SaveAndReimport(); + } + + private static void SetKeyword(Material material, string keyword, bool enabled) + { + if (enabled) material.EnableKeyword(keyword); + else material.DisableKeyword(keyword); + } + + private static bool GeneratePackedMask(TextureSet source, string outputPath) + { + ImageData rough = ReadImage(source.Roughness); + ImageData ao = ReadImage(source.AO); + ImageData metallic = ReadImage(source.Metalness); + ImageData packed = ReadImage(source.Packed); + if (rough == null && ao == null && metallic == null && packed == null) return false; + + int width = 1; + int height = 1; + foreach (ImageData img in new[] { rough, ao, metallic, packed }) + { + if (img == null) continue; + width = Math.Max(width, img.Width); + height = Math.Max(height, img.Height); + } + float scale = Mathf.Min(1f, (float)MegaScansURPImporterWindow.MaxPackedSize / Math.Max(width, height)); + width = Mathf.Max(1, Mathf.RoundToInt(width * scale)); + height = Mathf.Max(1, Mathf.RoundToInt(height * scale)); + + Color32[] pixels = new Color32[width * height]; + byte fallbackSmooth = (byte)Mathf.RoundToInt(MegaScansURPImporterWindow.DefaultSmoothness * 255f); + for (int y = 0; y < height; y++) + { + float v = (y + 0.5f) / height; + for (int x = 0; x < width; x++) + { + float u = (x + 0.5f) / width; + byte metal = metallic != null ? metallic.Sample(u, v, 0) : PackedMetal(packed, source.PackedKind, u, v); + byte occlusion = ao != null ? ao.Sample(u, v, 0) : PackedAO(packed, source.PackedKind, u, v); + byte roughness = rough != null ? rough.Sample(u, v, 0) : PackedRoughness(packed, source.PackedKind, u, v); + byte smoothness = rough != null || packed != null ? (byte)(255 - roughness) : fallbackSmooth; + pixels[y * width + x] = new Color32(metal, occlusion, 0, smoothness); + } + } + return WritePng(outputPath, width, height, pixels); + } + + private static byte PackedAO(ImageData packed, string kind, float u, float v) + { + if (packed == null) return 255; + if (kind == "RMA" || kind == "MRA") return packed.Sample(u, v, 2); + return packed.Sample(u, v, 0); + } + + private static byte PackedMetal(ImageData packed, string kind, float u, float v) + { + if (packed == null || kind == "ORD") return 0; + if (kind == "RMA") return packed.Sample(u, v, 1); + if (kind == "MRA") return packed.Sample(u, v, 0); + return packed.Sample(u, v, 2); + } + + private static byte PackedRoughness(ImageData packed, string kind, float u, float v) + { + if (packed == null) return (byte)Mathf.RoundToInt((1f - MegaScansURPImporterWindow.DefaultSmoothness) * 255f); + return packed.Sample(u, v, kind == "RMA" ? 0 : kind == "MRA" ? 1 : 1); + } + + private static bool GenerateBaseColorAlpha(string baseColor, string opacity, string outputPath) + { + ImageData color = ReadImage(baseColor); + ImageData alpha = ReadImage(opacity); + if (color == null || alpha == null) return false; + Color32[] pixels = new Color32[color.Pixels.Length]; + for (int y = 0; y < color.Height; y++) + { + float v = (y + 0.5f) / color.Height; + for (int x = 0; x < color.Width; x++) + { + float u = (x + 0.5f) / color.Width; + Color32 c = color.Pixels[y * color.Width + x]; + c.a = (byte)((c.a * alpha.Sample(u, v, 0) + 127) / 255); + pixels[y * color.Width + x] = c; + } + } + bool saved = WritePng(outputPath, color.Width, color.Height, pixels); + TextureImporter importer = AssetImporter.GetAtPath(outputPath) as TextureImporter; + if (importer != null && (!importer.sRGBTexture || !importer.alphaIsTransparency || importer.textureType != TextureImporterType.Default)) + { + importer.textureType = TextureImporterType.Default; + importer.sRGBTexture = true; + importer.alphaIsTransparency = true; + importer.SaveAndReimport(); + } + return saved; + } + + private static ImageData ReadImage(string assetPath) + { + if (string.IsNullOrEmpty(assetPath)) return null; + string extension = System.IO.Path.GetExtension(assetPath); + if (!string.Equals(extension, ".png", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".jpg", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase)) + { + Debug.LogWarning("MegaScans URP: Channel packing currently supports JPG/PNG inputs. Unsupported: " + assetPath); + return null; + } + string filePath = System.IO.Path.GetFullPath(assetPath); + if (!File.Exists(filePath)) return null; + Texture2D temporary = new Texture2D(2, 2, TextureFormat.RGBA32, false, true); + try + { + if (!ImageConversion.LoadImage(temporary, File.ReadAllBytes(filePath), false)) return null; + return new ImageData { Width = temporary.width, Height = temporary.height, Pixels = temporary.GetPixels32() }; + } + finally + { + UnityEngine.Object.DestroyImmediate(temporary); + } + } + + private static bool WritePng(string assetPath, int width, int height, Color32[] pixels) + { + Texture2D texture = new Texture2D(width, height, TextureFormat.RGBA32, false, true); + byte[] png; + try + { + texture.SetPixels32(pixels); + texture.Apply(false, false); + png = ImageConversion.EncodeToPNG(texture); + } + finally + { + UnityEngine.Object.DestroyImmediate(texture); + } + string filePath = System.IO.Path.GetFullPath(assetPath); + if (File.Exists(filePath) && File.ReadAllBytes(filePath).SequenceEqual(png)) return true; + File.WriteAllBytes(filePath, png); + AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); + return true; + } + } + + public sealed class MegaScansURPPostprocessor : AssetPostprocessor + { + public Material OnAssignMaterialModel(Material sourceMaterial, Renderer renderer) + { + if (!MegaScansURPProcessor.IsSourceModel(assetPath)) return null; + string directory = System.IO.Path.GetDirectoryName(assetPath).Replace('\\', '/'); + string name = System.IO.Path.GetFileNameWithoutExtension(assetPath); + string materialPath = directory + "/" + MegaScansURPImporterWindow.OutputFolder + "/" + name + "_URP.mat"; + return AssetDatabase.LoadAssetAtPath(materialPath); + } + + private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) + { + if (!MegaScansURPImporterWindow.AutoProcess) return; + MegaScansURPProcessor.EnqueueChangedAssets(importedAssets.Concat(movedAssets)); + } + } +} +#endif diff --git a/Assets/Scripts/Editor/PackageManager/PackageManagerFavorites.cs b/Assets/Scripts/Editor/PackageManager/PackageManagerFavorites.cs new file mode 100644 index 0000000..1ccc0f1 --- /dev/null +++ b/Assets/Scripts/Editor/PackageManager/PackageManagerFavorites.cs @@ -0,0 +1,326 @@ +// adds custom buttons into PackageManager left panel (tested in 6.5) +// edit your own favorites in the code + +#if UNITY_EDITOR +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEditor.Compilation; +using UnityEditor.PackageManager; +using UnityEditor.PackageManager.Requests; +using UnityEngine; +using UnityEngine.UIElements; + +namespace UnityLibrary.Editor.Tools +{ + + [InitializeOnLoad] + public static class PackageManagerFavorites + { + private const string InjectedElementName = "kelobyte-package-manager-dummy-panel"; + private static double nextScanTime; + private static AddRequest addRequest; + private static string pendingPackageName; + + static PackageManagerFavorites() + { + EditorApplication.update += OnEditorUpdate; + } + + [MenuItem("Window/Package Management/Open Package Manager With Dummy Button")] + private static void OpenPackageManagerAndInject() + { + Type windowType = GetPackageManagerWindowType(); + + if (windowType == null) + { + Debug.LogWarning("Package Manager window type was not found."); + return; + } + + EditorWindow window = EditorWindow.GetWindow(windowType); + window.Show(); + + EditorApplication.delayCall += TryInject; + } + + private static void OnEditorUpdate() + { + if (EditorApplication.timeSinceStartup < nextScanTime) + return; + + nextScanTime = EditorApplication.timeSinceStartup + 0.5; + TryInject(); + } + + private static void TryInject() + { + Type windowType = GetPackageManagerWindowType(); + + if (windowType == null) + return; + + UnityEngine.Object[] windows = Resources.FindObjectsOfTypeAll(windowType); + + foreach (UnityEngine.Object obj in windows) + { + EditorWindow window = obj as EditorWindow; + + if (window == null) + continue; + + InjectIntoWindow(window); + } + } + + private static Type GetPackageManagerWindowType() + { + Type type = Type.GetType("UnityEditor.PackageManager.UI.PackageManagerWindow, UnityEditor.PackageManagerUIModule"); + + if (type != null) + return type; + + foreach (System.Reflection.Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + type = assembly.GetType("UnityEditor.PackageManager.UI.PackageManagerWindow"); + + if (type != null) + return type; + } + + return null; + } + + private static void InjectIntoWindow(EditorWindow window) + { + VisualElement root = window.rootVisualElement; + + if (root == null) + return; + + if (root.Q(InjectedElementName) != null) + return; + + VisualElement insertParent = FindInsertParent(root); + int insertIndex = FindInsertIndex(insertParent); + + if (insertParent == null) + return; + + VisualElement panel = CreateDummyPanel(); + + if (insertIndex >= 0 && insertIndex <= insertParent.childCount) + insertParent.Insert(insertIndex, panel); + else + insertParent.Add(panel); + } + + private static VisualElement CreateDummyPanel() + { + VisualElement wrapper = new VisualElement(); + wrapper.name = InjectedElementName; + + wrapper.style.marginTop = 8; + wrapper.style.marginBottom = 8; + wrapper.style.paddingLeft = 6; + wrapper.style.paddingRight = 6; + + Foldout foldout = new Foldout(); + foldout.text = "Favorites"; + foldout.value = true; + + Button newtonsoftButton = CreatePackageButton( + "Newtonsoft Json", + "com.unity.nuget.newtonsoft-json" + ); + + Button gltfastButton = CreatePackageButton( + "Unity glTFast", + "com.unity.cloud.gltfast" + ); + + Button unityGltfButton = CreatePackageButton( + "Khronos UnityGLTF", + "https://github.com/KhronosGroup/UnityGLTF.git" + ); + + Button myEssentials = CreatePackageButton( + "Essentials", + " https://github.com/unitycoder/UnityEditorEssentials.git" + ); + + foldout.Add(newtonsoftButton); + foldout.Add(gltfastButton); + foldout.Add(unityGltfButton); + foldout.Add(myEssentials); + + wrapper.Add(foldout); + + return wrapper; + } + + private static Button CreatePackageButton(string label, string packageNameOrUrl) + { + Button button = new Button(() => + { + AddPackage(packageNameOrUrl); + }); + + button.text = label; + button.style.marginTop = 4; + button.style.height = 24; + + return button; + } + + private static void AddPackage(string packageNameOrUrl) + { + string packageToAdd = packageNameOrUrl.Trim(); + + if (addRequest != null && !addRequest.IsCompleted) + { + Debug.LogWarning("A package add request is already in progress."); + return; + } + + Debug.Log($"Adding package: {packageToAdd}"); + + pendingPackageName = packageToAdd; + addRequest = Client.Add(packageToAdd); + + EditorApplication.update -= MonitorAddPackageRequest; + EditorApplication.update += MonitorAddPackageRequest; + } + + private static void MonitorAddPackageRequest() + { + if (addRequest == null || !addRequest.IsCompleted) + return; + + EditorApplication.update -= MonitorAddPackageRequest; + + if (addRequest.Status == StatusCode.Success) + { + Debug.Log($"Package added: {pendingPackageName}"); + Client.Resolve(); + AssetDatabase.Refresh(); + CompilationPipeline.RequestScriptCompilation(); + } + else + { + string errorMessage = addRequest.Error != null ? addRequest.Error.message : "Unknown error."; + Debug.LogError($"Failed to add package '{pendingPackageName}': {errorMessage}"); + } + + addRequest = null; + pendingPackageName = null; + } + + private static VisualElement FindInsertParent(VisualElement root) + { + Label servicesLabel = FindLabel(root, "Services"); + + if (servicesLabel != null && servicesLabel.parent != null && servicesLabel.parent.parent != null) + return servicesLabel.parent.parent; + + Label cloudLabel = FindLabel(root, "Cloud"); + + if (cloudLabel != null && cloudLabel.parent != null && cloudLabel.parent.parent != null) + return cloudLabel.parent.parent; + + Label sourcesLabel = FindLabel(root, "Sources"); + + if (sourcesLabel != null && sourcesLabel.parent != null && sourcesLabel.parent.parent != null) + return sourcesLabel.parent.parent; + + return FindLikelyLeftPanel(root); + } + + private static int FindInsertIndex(VisualElement parent) + { + if (parent == null) + return -1; + + for (int i = 0; i < parent.childCount; i++) + { + VisualElement child = parent[i]; + + if (ContainsLabel(child, "Services")) + return i + 1; + } + + for (int i = 0; i < parent.childCount; i++) + { + VisualElement child = parent[i]; + + if (ContainsLabel(child, "Cloud")) + return i + 1; + } + + return -1; + } + + private static VisualElement FindLikelyLeftPanel(VisualElement root) + { + List all = new List(); + Collect(root, all); + + foreach (VisualElement element in all) + { + Rect rect = element.worldBound; + + if (rect.width > 120 && rect.width < 260 && rect.height > 250 && rect.x < 250) + return element; + } + + return null; + } + + private static Label FindLabel(VisualElement root, string text) + { + List all = new List(); + Collect(root, all); + + foreach (VisualElement element in all) + { + Label label = element as Label; + + if (label != null && label.text == text) + return label; + } + + return null; + } + + private static bool ContainsLabel(VisualElement root, string text) + { + if (root == null) + return false; + + Label label = root as Label; + + if (label != null && label.text == text) + return true; + + for (int i = 0; i < root.childCount; i++) + { + if (ContainsLabel(root[i], text)) + return true; + } + + return false; + } + + private static void Collect(VisualElement root, List elements) + { + if (root == null) + return; + + elements.Add(root); + + for (int i = 0; i < root.childCount; i++) + Collect(root[i], elements); + } + } +} +#endif diff --git a/Assets/Scripts/Editor/ProjectWindow/UnityIgnore.cs b/Assets/Scripts/Editor/ProjectWindow/UnityIgnore.cs new file mode 100644 index 0000000..098c878 --- /dev/null +++ b/Assets/Scripts/Editor/ProjectWindow/UnityIgnore.cs @@ -0,0 +1,442 @@ +// UnityIgnore.cs - put this in any "Editor" folder. +// +// Hides files and folders from the Project window, driven by a gitignore-style +// ".unityignore" file in the project root (next to Assets/). +// +// Display only: hidden assets are still imported, referenced and built as usual. +// Toggle: Assets > Unity Ignore > Hide Ignored Files (Ctrl+Alt+H), also in the Project right-click menu. +// +// Unity has no public API for this, so the script filters the Project Browser's internal +// row lists through reflection. Member names were checked against the UnityCsReference +// source for 6000.0 - 6000.7. If they ever change, it logs one warning and switches itself off. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditor; +using UnityEditorInternal; +using UnityEngine; + +namespace UnityLibrary.UnityIgnore +{ + [InitializeOnLoad] + static class UnityIgnore + { + const string IgnoreFile = ".unityignore"; + const string PrefKey = "UnityIgnore.Enabled"; + const string ToggleName = "Assets/Unity Ignore/Hide Ignored Files"; + const string ToggleMenu = ToggleName + " %&h"; + const string EditMenu = "Assets/Unity Ignore/Edit .unityignore"; + + const string Template = + "# .unityignore - hides matching files and folders from the Project window.\n" + + "# gitignore syntax, paths relative to the project root, not case sensitive.\n" + + "# Hidden assets are still imported and usable.\n" + + "#\n" + + "# desktop.ini\n" + + "# *.psd\n" + + "# /Assets/ScriptTemplates/\n"; + + const BindingFlags Declared = + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + + struct Rule + { + public Regex regex; + public bool negate, dirOnly; + } + + static readonly List s_Rules = new List(); + static readonly Dictionary s_Cache = new Dictionary(); + + // Objects already handled: filtered row lists / result arrays, and data sources that carry our hook. + static readonly ConditionalWeakTable s_Seen = new ConditionalWeakTable(); + + static IList s_Browsers; + static MethodInfo s_ResetViews; + static bool s_Enabled, s_Broken; + static DateTime s_FileTime; + static double s_NextFileCheck; + + static UnityIgnore() + { + s_Enabled = EditorUserSettings.GetConfigValue(PrefKey) != "0"; + LoadRules(); + EditorApplication.update += Tick; + EditorApplication.projectChanged += s_Cache.Clear; + } + + // ------------------------------------------------------------------ menu + + [MenuItem(ToggleMenu, false, 2000)] + static void Toggle() + { + s_Enabled = !s_Enabled; + EditorUserSettings.SetConfigValue(PrefKey, s_Enabled ? "1" : "0"); + Refresh(); + } + + [MenuItem(ToggleMenu, true)] + static bool ToggleValidate() + { + Menu.SetChecked(ToggleName, s_Enabled); + return true; + } + + [MenuItem(EditMenu, false, 2001)] + static void Edit() + { + if (!File.Exists(IgnoreFile)) + File.WriteAllText(IgnoreFile, Template); + InternalEditorUtility.OpenFileAtLineExternal(Path.GetFullPath(IgnoreFile), 1); + } + + // ------------------------------------------------------------------ rules + + static void LoadRules() + { + string[] lines; + try + { + s_FileTime = File.GetLastWriteTimeUtc(IgnoreFile); // a missing file has a stable timestamp too + lines = File.Exists(IgnoreFile) ? File.ReadAllLines(IgnoreFile) : new string[0]; + } + catch (IOException) + { + s_FileTime = DateTime.MinValue; // file is mid-save, try again on the next check + return; + } + + s_Rules.Clear(); + s_Cache.Clear(); + + for (int n = 0; n < lines.Length; n++) + { + string line = lines[n].Trim(); + if (line.Length == 0 || line[0] == '#') + continue; + + Rule rule = new Rule(); + rule.negate = line[0] == '!'; + if (rule.negate) + line = line.Substring(1); + + rule.dirOnly = line.EndsWith("/"); + line = line.TrimEnd('/'); + bool anchored = line.Contains("/"); // "/x" or "a/x" starts at the project root, plain "x" matches at any depth + line = line.TrimStart('/'); + if (line.Length == 0) + continue; + + try + { + rule.regex = new Regex(GlobToRegex(line, anchored), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + s_Rules.Add(rule); + } + catch (ArgumentException) + { + Debug.LogWarning("[UnityIgnore] Skipping bad pattern on line " + (n + 1) + ": " + lines[n]); + } + } + } + + static string GlobToRegex(string glob, bool anchored) + { + StringBuilder sb = new StringBuilder(anchored ? "^" : "^(?:.*/)?"); + + for (int i = 0; i < glob.Length; i++) + { + char c = glob[i]; + int close = c == '[' && i + 2 < glob.Length ? glob.IndexOf(']', i + 2) : -1; + + if (c == '*' && i + 1 < glob.Length && glob[i + 1] == '*') + { + i++; + if (i + 1 < glob.Length && glob[i + 1] == '/') + { + i++; + sb.Append("(?:.*/)?"); // "**/" = any number of folders, including none + } + else + { + sb.Append(".*"); + } + } + else if (c == '*') + { + sb.Append("[^/]*"); + } + else if (c == '?') + { + sb.Append("[^/]"); + } + else if (close > 0) + { + string set = glob.Substring(i + 1, close - i - 1); + bool not = set[0] == '!' || set[0] == '^'; + if (not) + set = set.Substring(1); + set = set.Replace("\\", "\\\\").Replace("[", "\\[").Replace("]", "\\]").Replace("^", "\\^"); + sb.Append(not ? "[^" : "[").Append(set).Append(']'); + i = close; + } + else + { + if (c == '\\' && i + 1 < glob.Length) + c = glob[++i]; + sb.Append(Regex.Escape(c.ToString())); + } + } + + return sb.Append('$').ToString(); + } + + static bool IsHidden(string guid) + { + return !string.IsNullOrEmpty(guid) && IsIgnored(AssetDatabase.GUIDToAssetPath(guid)); + } + + static bool IsIgnored(string path) + { + if (string.IsNullOrEmpty(path)) + return false; + + bool ignored; + if (s_Cache.TryGetValue(path, out ignored)) + return ignored; + + // A hidden folder hides everything inside it. Otherwise the last matching rule wins. + int slash = path.LastIndexOf('/'); + ignored = slash > 0 && IsIgnored(path.Substring(0, slash)); + if (!ignored) + { + bool isDir = AssetDatabase.IsValidFolder(path); + foreach (Rule rule in s_Rules) + if ((isDir || !rule.dirOnly) && rule.regex.IsMatch(path)) + ignored = !rule.negate; + } + + s_Cache[path] = ignored; + return ignored; + } + + // ------------------------------------------------------------------ project window + + static void Tick() + { + try + { + // Pick up edits to .unityignore (checked once a second). + if (EditorApplication.timeSinceStartup >= s_NextFileCheck) + { + s_NextFileCheck = EditorApplication.timeSinceStartup + 1; + if (File.GetLastWriteTimeUtc(IgnoreFile) != s_FileTime) + { + LoadRules(); + if (s_Enabled) + Refresh(); + return; + } + } + + FilterAll(); + } + catch (Exception e) + { + Fail(e); + } + } + + static bool Active + { + get { return s_Enabled && !s_Broken && s_Rules.Count > 0; } + } + + static IList Browsers() + { + if (s_Browsers == null) + { + Type type = typeof(EditorWindow).Assembly.GetType("UnityEditor.ProjectBrowser", true); + s_ResetViews = type.GetMethod("ResetViews", BindingFlags.Instance | BindingFlags.NonPublic); + s_Browsers = (IList)type.GetMethod("GetAllProjectBrowsers").Invoke(null, null); + } + return s_Browsers; + } + + static void FilterAll() + { + if (!Active) + return; + + foreach (object browser in Browsers()) + { + FilterTree(Get(browser, "m_AssetTree")); // one column layout + FilterTree(Get(browser, "m_FolderTree")); // two column layout: folder tree + FilterList(browser); // two column layout: right pane, and search results + } + } + + // Rebuilds every Project window, the same way Unity does after an asset change. + static void Refresh() + { + s_Cache.Clear(); + try + { + foreach (EditorWindow browser in Browsers()) + { + s_ResetViews.Invoke(browser, null); + browser.Repaint(); + } + FilterAll(); + } + catch (Exception e) + { + Fail(e); + } + } + + static void FilterTree(object tree) + { + object data = Get(tree, "data"); + if (data == null) + return; + + if (FirstTime(data)) + { + // Expanding or collapsing a folder rebuilds the rows lazily inside OnGUI. + // This callback fires right after that, so nothing flashes. + Action hook = delegate { FilterRows(data); }; + Set(data, "onVisibleRowsChanged", Delegate.Combine((Delegate)Get(data, "onVisibleRowsChanged"), hook)); + } + + FilterRows(data); // covers the rebuilds that skip the callback (ReloadData and friends) + } + + static void FilterRows(object data) + { + if (!Active) + return; + + try + { + IList rows = Get(data, "m_Rows") as IList; + if (rows == null || !FirstTime(rows)) + return; + + for (int i = rows.Count - 1; i >= 0; i--) + { + object item = rows[i]; + if (!IsHidden(Get(item, "Guid", true) as string)) + continue; + + rows.RemoveAt(i); + + // Also detach it from its parent, so a folder with nothing visible left loses its foldout arrow. + IList siblings = Get(Get(item, "parent"), "children") as IList; + if (siblings != null) + siblings.Remove(item); + } + } + catch (Exception e) + { + Fail(e); + } + } + + static void FilterList(object browser) + { + object hierarchy = Get(Get(Get(browser, "m_ListArea"), "m_LocalAssets"), "m_FilteredHierarchy"); + if (hierarchy == null) + return; + + // Single "|" on purpose: both arrays have to be stripped. + if (Strip(hierarchy, "m_Results") | Strip(hierarchy, "m_VisibleItems")) + ((EditorWindow)browser).Repaint(); + } + + static bool Strip(object hierarchy, string field) + { + Array items = Get(hierarchy, field) as Array; + if (items == null || !FirstTime(items)) + return false; + + List kept = new List(items.Length); + foreach (object item in items) + if (!IsHidden(Get(item, "guid") as string)) + kept.Add(item); + + if (kept.Count == items.Length) + return false; + + Array filtered = Array.CreateInstance(items.GetType().GetElementType(), kept.Count); + for (int i = 0; i < kept.Count; i++) + filtered.SetValue(kept[i], i); + + FirstTime(filtered); + Set(hierarchy, field, filtered); + return true; + } + + // ------------------------------------------------------------------ helpers + + static bool FirstTime(object obj) + { + object unused; + if (s_Seen.TryGetValue(obj, out unused)) + return false; + s_Seen.Add(obj, null); + return true; + } + + // Reads a field or property by name, searching base classes too. Null in, null out. + static object Get(object obj, string name, bool optional = false) + { + if (obj == null) + return null; + + for (Type type = obj.GetType(); type != null; type = type.BaseType) + { + FieldInfo field = type.GetField(name, Declared); + if (field != null) + return field.GetValue(obj); + + PropertyInfo property = type.GetProperty(name, Declared); + if (property != null) + return property.GetValue(obj, null); + } + + if (optional) + return null; + throw new MissingMemberException(obj.GetType().Name, name); + } + + static void Set(object obj, string name, object value) + { + for (Type type = obj.GetType(); type != null; type = type.BaseType) + { + FieldInfo field = type.GetField(name, Declared); + if (field != null) + { + field.SetValue(obj, value); + return; + } + } + throw new MissingMemberException(obj.GetType().Name, name); + } + + static void Fail(Exception e) + { + if (s_Broken) + return; + + s_Broken = true; + EditorApplication.update -= Tick; + Debug.LogWarning("[UnityIgnore] The Project window internals look different in this Unity version, so hiding is switched off.\n" + e); + } + } +} diff --git a/Assets/Scripts/Editor/Tools/AndroidStoreCaptureTool.cs b/Assets/Scripts/Editor/Tools/AndroidStoreCaptureTool.cs new file mode 100644 index 0000000..8a73f3a --- /dev/null +++ b/Assets/Scripts/Editor/Tools/AndroidStoreCaptureTool.cs @@ -0,0 +1,513 @@ +// AndroidStoreCaptureTool.cs +// Put this file anywhere under an "Editor" folder. +// Usage: +// 1) Enter Play Mode. +// 2) Open: Tools/Android Store Capture +// 3) Pick output folder and click "Capture All Presets" + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using UnityEditor; +using UnityEngine; + +namespace UnityLibrary.Tools +{ + public class AndroidStoreCaptureTool : EditorWindow + { + [Serializable] + private class Preset + { + public string name; // base file name (without _WxH) + public int width; + public int height; + public CropMode cropMode; + + public Preset(string name, int w, int h, CropMode cropMode) + { + this.name = name; + width = w; + height = h; + this.cropMode = cropMode; + } + } + + private enum CropMode + { + Stretch, // no crop, just scale to target (may distort) + CropToFit // center-crop to target aspect, then scale (no distortion) + } + + private string _outputFolder = "StoreCaptures"; + private int _phoneCount = 2; // Play Console: 2-8 phone screenshots + + // Jobs + private class CaptureJob + { + public Preset preset; + public string filename; + } + + private readonly Queue _queue = new Queue(); + private bool _isRunning; + + // Hidden helper MonoBehaviour that runs coroutines in Play Mode + private CaptureHelper _helper; + + // Presets based on Play Console rules in your message. + // Phone/tablet sizes are common choices within allowed ranges. + private List BuildPresets() + { + var list = new List(); + + // App icon and feature graphic + list.Add(new Preset("appicon", 512, 512, CropMode.CropToFit)); + list.Add(new Preset("featuregraphic", 1024, 500, CropMode.CropToFit)); + + // Phone screenshots (2-8). 9:16 or 16:9. Each side 320..3840. + // We capture portrait by default; toggle to landscape if you want. + for (int i = 1; i <= Mathf.Clamp(_phoneCount, 2, 8); i++) + list.Add(new Preset("phone_" + i.ToString("00"), 1080, 1920, CropMode.CropToFit)); + + // 7-inch tablet screenshots (allowed: 320..3840 each side) + list.Add(new Preset("tablet7_01", 1920, 1200, CropMode.CropToFit)); // landscape 16:10 + list.Add(new Preset("tablet7_02", 1200, 1920, CropMode.CropToFit)); // portrait 10:16 + + // 10-inch tablet screenshots (each side 1080..7680) + list.Add(new Preset("tablet10_01", 2560, 1600, CropMode.CropToFit)); // landscape 16:10 + list.Add(new Preset("tablet10_02", 1600, 2560, CropMode.CropToFit)); // portrait 10:16 + + return list; + } + + [MenuItem("Tools/Android Store Capture")] + public static void Open() + { + var w = GetWindow("Android Store Capture"); + w.minSize = new Vector2(420, 340); + w.Show(); + } + + private void OnDisable() + { + StopRunner(); + } + + private void OnGUI() + { + EditorGUILayout.LabelField("Capture from Game View (Play Mode)", EditorStyles.boldLabel); + + using (new EditorGUILayout.VerticalScope("box")) + { + EditorGUILayout.LabelField("Output", EditorStyles.boldLabel); + + EditorGUILayout.BeginHorizontal(); + _outputFolder = EditorGUILayout.TextField("Folder", _outputFolder); + if (GUILayout.Button("Browse", GUILayout.Width(80))) + { + string picked = EditorUtility.OpenFolderPanel("Pick output folder", Application.dataPath, ""); + if (!string.IsNullOrEmpty(picked)) + { + // Make it project-relative when possible + string proj = Path.GetFullPath(Path.Combine(Application.dataPath, "..")); + string full = Path.GetFullPath(picked); + if (full.StartsWith(proj, StringComparison.OrdinalIgnoreCase)) + { + _outputFolder = full.Substring(proj.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + } + else + { + _outputFolder = full; + } + } + } + EditorGUILayout.EndHorizontal(); + + _phoneCount = EditorGUILayout.IntSlider("Phone screenshots (2-8)", _phoneCount, 2, 8); + } + + using (new EditorGUILayout.VerticalScope("box")) + { + EditorGUILayout.LabelField("Actions", EditorStyles.boldLabel); + + if (!EditorApplication.isPlaying) + { + EditorGUILayout.HelpBox("Enter Play Mode first. This tool captures the rendered Game View.", MessageType.Warning); + } + + GUI.enabled = EditorApplication.isPlaying && !_isRunning; + if (GUILayout.Button("Capture All Presets")) + { + EnqueueAll(); + StartRunner(); + } + + if (GUILayout.Button("Capture Only Icon + Feature Graphic")) + { + EnqueueIconAndFeatureOnly(); + StartRunner(); + } + GUI.enabled = true; + + GUI.enabled = _isRunning; + if (GUILayout.Button("Stop")) + { + StopRunner(); + } + GUI.enabled = true; + + if (_isRunning) + { + EditorGUILayout.Space(6); + EditorGUILayout.LabelField("Running...", EditorStyles.boldLabel); + EditorGUILayout.LabelField("Remaining", _queue.Count.ToString()); + } + } + + using (new EditorGUILayout.VerticalScope("box")) + { + EditorGUILayout.LabelField("Notes", EditorStyles.boldLabel); + EditorGUILayout.LabelField("- Files are named like: appicon_512x512.png, featuregraphic_1024x500.png"); + EditorGUILayout.LabelField("- Phone screenshots are named like: phone_01_1080x1920.png"); + EditorGUILayout.LabelField("- Captures center-crop to match target aspect (no stretching)."); + } + } + + private void EnqueueAll() + { + _queue.Clear(); + + string folder = ResolveOutputFolder(); + Directory.CreateDirectory(folder); + + foreach (var p in BuildPresets()) + { + string fn = $"{p.name}_{p.width}x{p.height}.png"; + _queue.Enqueue(new CaptureJob { preset = p, filename = Path.Combine(folder, fn) }); + } + } + + private void EnqueueIconAndFeatureOnly() + { + _queue.Clear(); + + string folder = ResolveOutputFolder(); + Directory.CreateDirectory(folder); + + var icon = new Preset("appicon", 512, 512, CropMode.CropToFit); + var feature = new Preset("featuregraphic", 1024, 500, CropMode.CropToFit); + + _queue.Enqueue(new CaptureJob { preset = icon, filename = Path.Combine(folder, $"appicon_512x512.png") }); + _queue.Enqueue(new CaptureJob { preset = feature, filename = Path.Combine(folder, $"featuregraphic_1024x500.png") }); + } + + private string ResolveOutputFolder() + { + // If user gave absolute path, use it. Otherwise, place under project root. + if (Path.IsPathRooted(_outputFolder)) + return _outputFolder; + + string projectRoot = Path.GetFullPath(Path.Combine(Application.dataPath, "..")); + return Path.Combine(projectRoot, _outputFolder); + } + + private CaptureHelper EnsureHelper() + { + if (_helper != null) return _helper; + + var go = new GameObject("[AndroidStoreCaptureHelper]") + { + hideFlags = HideFlags.HideAndDontSave + }; + _helper = go.AddComponent(); + return _helper; + } + + private void StartRunner() + { + if (_isRunning) return; + if (!EditorApplication.isPlaying) return; + + _isRunning = true; + + GetMainGameView(); + + var helper = EnsureHelper(); + helper.StartCoroutine(RunCaptures()); + } + + private void StopRunner() + { + _isRunning = false; + _queue.Clear(); + + if (_helper != null) + { + _helper.StopAllCoroutines(); + DestroyImmediate(_helper.gameObject); + _helper = null; + } + } + + private IEnumerator RunCaptures() + { + while (_queue.Count > 0) + { + if (!EditorApplication.isPlaying) + { + StopRunner(); + yield break; + } + + var job = _queue.Dequeue(); + + SetGameViewSize(job.preset.width, job.preset.height); + + // Wait for the GameView to resize and re-render + for (int i = 0; i < 6; i++) + yield return null; + + // Wait for end of frame — this is required for ScreenCapture to work + yield return new WaitForEndOfFrame(); + + try + { + ProcessCaptureJob(job); + } + catch (Exception ex) + { + Debug.LogError("Capture failed: " + ex); + } + + Repaint(); + } + + _isRunning = false; + AssetDatabase.Refresh(); + Debug.Log("Android Store Capture: All captures finished."); + Repaint(); + + if (_helper != null) + { + DestroyImmediate(_helper.gameObject); + _helper = null; + } + } + + private void ProcessCaptureJob(CaptureJob job) + { + int targetW = job.preset.width; + int targetH = job.preset.height; + + Texture2D src = ScreenCapture.CaptureScreenshotAsTexture(); + if (src == null) + { + Debug.LogError($"CaptureScreenshotAsTexture returned null for {job.filename}. Skipping."); + return; + } + + Texture2D processed; + if (job.preset.cropMode == CropMode.CropToFit) + processed = CropToAspectThenScale(src, targetW, targetH); + else + processed = ScaleTexture(src, targetW, targetH); + + byte[] png = processed.EncodeToPNG(); + File.WriteAllBytes(job.filename, png); + + DestroyImmediate(src); + if (processed != src) + DestroyImmediate(processed); + + Debug.Log("Saved: " + job.filename); + } + + private static Texture2D CropToAspectThenScale(Texture2D src, int targetW, int targetH) + { + float srcAspect = (float)src.width / src.height; + float dstAspect = (float)targetW / targetH; + + int cropW = src.width; + int cropH = src.height; + + if (srcAspect > dstAspect) + { + // too wide -> crop width + cropW = Mathf.RoundToInt(src.height * dstAspect); + cropH = src.height; + } + else + { + // too tall -> crop height + cropW = src.width; + cropH = Mathf.RoundToInt(src.width / dstAspect); + } + + // Crop from top-left: x starts at 0, y starts from top + int x0 = 0; + int y0 = src.height - cropH; + + Color[] pixels = src.GetPixels(x0, y0, cropW, cropH); + Texture2D cropped = new Texture2D(cropW, cropH, TextureFormat.RGBA32, false); + cropped.SetPixels(pixels); + cropped.Apply(false, false); + + Texture2D scaled = ScaleTexture(cropped, targetW, targetH); + DestroyImmediate(cropped); + return scaled; + } + + private static Texture2D ScaleTexture(Texture2D src, int targetW, int targetH) + { + Texture2D dst = new Texture2D(targetW, targetH, TextureFormat.RGBA32, false); + + for (int y = 0; y < targetH; y++) + { + float v = (targetH == 1) ? 0f : (float)y / (targetH - 1); + for (int x = 0; x < targetW; x++) + { + float u = (targetW == 1) ? 0f : (float)x / (targetW - 1); + Color c = SampleBilinear(src, u, v); + dst.SetPixel(x, y, c); + } + } + + dst.Apply(false, false); + return dst; + } + + private static Color SampleBilinear(Texture2D tex, float u, float v) + { + float x = u * (tex.width - 1); + float y = v * (tex.height - 1); + + int x0 = Mathf.Clamp((int)Mathf.Floor(x), 0, tex.width - 1); + int y0 = Mathf.Clamp((int)Mathf.Floor(y), 0, tex.height - 1); + int x1 = Mathf.Clamp(x0 + 1, 0, tex.width - 1); + int y1 = Mathf.Clamp(y0 + 1, 0, tex.height - 1); + + float tx = x - x0; + float ty = y - y0; + + Color c00 = tex.GetPixel(x0, y0); + Color c10 = tex.GetPixel(x1, y0); + Color c01 = tex.GetPixel(x0, y1); + Color c11 = tex.GetPixel(x1, y1); + + Color a = Color.Lerp(c00, c10, tx); + Color b = Color.Lerp(c01, c11, tx); + return Color.Lerp(a, b, ty); + } + + // --------------------------- + // GameView sizing (internal) + // --------------------------- + + private static EditorWindow GetMainGameView() + { + Type t = Type.GetType("UnityEditor.GameView,UnityEditor"); + if (t == null) return null; + + // Try "GetMainGameView" first (older Unity versions) + MethodInfo getMain = t.GetMethod("GetMainGameView", BindingFlags.NonPublic | BindingFlags.Static); + if (getMain != null) + { + var result = getMain.Invoke(null, null) as EditorWindow; + if (result != null) return result; + } + + // Fallback: try "GetMainGameViewRenderRect" or just find an open GameView window + var gameView = GetWindow(t, false, null, false); + return gameView; + } + + private static void SetGameViewSize(int width, int height) + { + // Creates/uses a fixed resolution entry in the current platform group, then selects it. + // Unity does not expose this publicly; reflection is used. + + Type sizesType = Type.GetType("UnityEditor.GameViewSizes,UnityEditor"); + Type sizeType = Type.GetType("UnityEditor.GameViewSize,UnityEditor"); + Type groupType = Type.GetType("UnityEditor.GameViewSizeGroupType,UnityEditor"); + + if (sizesType == null || sizeType == null || groupType == null) + return; + + var instanceProp = sizesType.GetProperty("instance", BindingFlags.Public | BindingFlags.Static); + if (instanceProp == null) return; + object sizesInstance = instanceProp.GetValue(null, null); + if (sizesInstance == null) return; + + MethodInfo getGroup = sizesType.GetMethod("GetGroup"); + if (getGroup == null) return; + object group = getGroup.Invoke(sizesInstance, new object[] { (int)Enum.Parse(groupType, "Standalone") }); + if (group == null) return; + + // Find existing + MethodInfo getBuiltinCount = group.GetType().GetMethod("GetBuiltinCount"); + MethodInfo getCustomCount = group.GetType().GetMethod("GetCustomCount"); + MethodInfo getGameViewSize = group.GetType().GetMethod("GetGameViewSize"); + + if (getBuiltinCount == null || getCustomCount == null || getGameViewSize == null) return; + + int builtin = (int)getBuiltinCount.Invoke(group, null); + int custom = (int)getCustomCount.Invoke(group, null); + + int total = builtin + custom; + int foundIndex = -1; + + for (int i = 0; i < total; i++) + { + object gvSize = getGameViewSize.Invoke(group, new object[] { i }); + if (gvSize == null) continue; + var widthProp = gvSize.GetType().GetProperty("width"); + var heightProp = gvSize.GetType().GetProperty("height"); + if (widthProp == null || heightProp == null) continue; + + int w = (int)widthProp.GetValue(gvSize, null); + int h = (int)heightProp.GetValue(gvSize, null); + + if (w == width && h == height) + { + foundIndex = i; + break; + } + } + + if (foundIndex < 0) + { + // Add custom size + Type gvSizeType = Type.GetType("UnityEditor.GameViewSizeType,UnityEditor"); + if (gvSizeType == null) return; + object fixedRes = Enum.Parse(gvSizeType, "FixedResolution"); + + ConstructorInfo ctor = sizeType.GetConstructor(new[] { gvSizeType, typeof(int), typeof(int), typeof(string) }); + if (ctor == null) return; + object newSize = ctor.Invoke(new object[] { fixedRes, width, height, width + "x" + height }); + + MethodInfo addCustom = group.GetType().GetMethod("AddCustomSize"); + if (addCustom == null) return; + addCustom.Invoke(group, new object[] { newSize }); + + custom = (int)getCustomCount.Invoke(group, null); + foundIndex = builtin + (custom - 1); + } + + // Select size in GameView + EditorWindow gv = GetMainGameView(); + if (gv == null) return; + + Type gvType = gv.GetType(); + PropertyInfo selectedSizeIndex = gvType.GetProperty("selectedSizeIndex", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (selectedSizeIndex != null) + selectedSizeIndex.SetValue(gv, foundIndex, null); + + gv.Repaint(); + } + + // Hidden MonoBehaviour to run coroutines from the editor tool + private class CaptureHelper : MonoBehaviour { } + } +} diff --git a/Assets/Scripts/Editor/Tools/CrossProjectHierarchyClipboard.cs b/Assets/Scripts/Editor/Tools/CrossProjectHierarchyClipboard.cs new file mode 100644 index 0000000..6118b43 --- /dev/null +++ b/Assets/Scripts/Editor/Tools/CrossProjectHierarchyClipboard.cs @@ -0,0 +1,1047 @@ +// CrossProjectHierarchyClipboard.cs +// Place this file in Assets/Editor in BOTH Unity projects. +// Intended for Unity 2019.4 through Unity 7 (7000.x). +// Cross-project transfer uses the operating system's text clipboard. +// This copies scene GameObjects, not prefab links or asset file contents. + +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; +using UnityEngine.SceneManagement; +using Object = UnityEngine.Object; + +namespace UnityLibrary.EditorTools +{ + public static class CrossProjectHierarchyClipboard + { + private const string ClipboardHeader = "UNITY_CROSS_PROJECT_HIERARCHY_V1\n"; + private const int FormatVersion = 1; + private const int MaximumObjects = 100000; + + // If an asset's GUID/path cannot be found, allow a unique match by + // asset name and type. Ambiguous matches are deliberately rejected. + private const bool AllowUniqueAssetNameFallback = true; + + [Serializable] + private class Package + { + public int version = FormatVersion; + public string sourceUnityVersion; + public List nodes = new List(); + } + + [Serializable] + private class Node + { + public int id; + public int parentId = -1; + public string name; + public bool active; + public string tag; + public string layerName; + public int layer; + public int staticFlags; + public Vector3 localPosition; + public Quaternion localRotation; + public Vector3 localScale; + public Vector3 worldPosition; + public Quaternion worldRotation; + public Vector3 worldScale; + public bool hasRectTransform; + public Vector2 anchorMin; + public Vector2 anchorMax; + public Vector2 pivot; + public Vector2 sizeDelta; + public Vector2 anchoredPosition; + public List parts = new List(); + } + + [Serializable] + private class Part + { + public int componentIndex; + public string typeFullName; + public string assemblyName; + public bool isTransform; + public List fields = new List(); + } + + [Serializable] + private class Field + { + public string path; + public string kind; + public string stringValue; + public string enumName; + public long integerValue; + public double doubleValue; + public bool boolValue; + public Color color; + public Vector2 vector2; + public Vector3 vector3; + public Vector4 vector4; + public Quaternion quaternion; + public Rect rect; + public Bounds bounds; + public Vector2Int vector2Int; + public Vector3Int vector3Int; + public RectInt rectInt; + public BoundsInt boundsInt; + public AnimationCurve curve; + public GradientColorKey[] gradientColors; + public GradientAlphaKey[] gradientAlphas; + public int gradientMode; + public Reference reference; + } + + [Serializable] + private class Reference + { + public string kind; // null, hierarchy, asset, external + public int nodeId; + public int componentIndex = -1; // -1 = GameObject + public string name; + public string typeFullName; + public string assemblyName; + public string guid; + public long localFileId; + public string path; + } + + private class CaptureContext + { + public readonly Dictionary nodeIds = new Dictionary(); + public readonly List orderedObjects = new List(); + public readonly Dictionary componentRefs = new Dictionary(); + } + + private class PasteContext + { + public readonly Dictionary nodes = new Dictionary(); + public readonly Dictionary components = new Dictionary(); + public readonly Dictionary assetCache = new Dictionary(); + public readonly HashSet warnings = new HashSet(); + public int componentsAdded; + public int missingComponents; + public int missingReferences; + public int skippedFields; + + public void Warn(string message) + { + // Limit log spam for large selections. + if (warnings.Count < 20) + warnings.Add(message); + } + } + + [MenuItem("Tools/Cross-Project Hierarchy/Copy Selected %&c", false, 1)] + public static void CopySelected() + { + var selected = Selection.gameObjects.Where(go => go && go.scene.IsValid()).ToArray(); + if (selected.Length == 0) + { + Debug.LogWarning("Cross-Project Hierarchy: Select one or more scene GameObjects to copy."); + return; + } + + var selectedSet = new HashSet(selected); + var roots = selected.Where(go => !HasSelectedAncestor(go.transform, selectedSet)) + .OrderBy(go => GetHierarchySortKey(go.transform), StringComparer.Ordinal) + .ToArray(); + + var package = new Package { sourceUnityVersion = Application.unityVersion }; + var context = new CaptureContext(); + + // Pass 1: collect the complete hierarchy and stable IDs. + foreach (var root in roots) + CaptureStructure(root.transform, -1, package, context); + + if (package.nodes.Count > MaximumObjects) + { + Debug.LogError("Cross-Project Hierarchy: Selection is too large to copy safely."); + return; + } + + // Pass 2: gather component properties and their portable references. + foreach (var node in package.nodes) + { + var sourceGo = context.orderedObjects[node.id]; + var components = sourceGo.GetComponents(); + for (int index = 0; index < components.Length; ++index) + { + var component = components[index]; + if (!component) // Missing script in the source project. + continue; + + var type = component.GetType(); + var part = new Part + { + componentIndex = index, + typeFullName = type.FullName, + assemblyName = type.Assembly.GetName().Name, + isTransform = component is Transform + }; + + if (!part.isTransform) + CaptureFields(component, part, context); + node.parts.Add(part); + } + } + + string json = JsonUtility.ToJson(package); + EditorGUIUtility.systemCopyBuffer = ClipboardHeader + json; + Debug.Log(string.Format( + "Cross-Project Hierarchy: Copied {0} GameObjects ({1} root objects) to the system clipboard, {2:N0} characters.", + package.nodes.Count, roots.Length, json.Length)); + } + + [MenuItem("Tools/Cross-Project Hierarchy/Copy Selected %&c", true)] + private static bool ValidateCopy() { return Selection.gameObjects.Any(go => go && go.scene.IsValid()); } + + [MenuItem("Tools/Cross-Project Hierarchy/Paste Under Selected %&v", false, 2)] + public static void PasteUnderSelected() + { + var parent = Selection.activeTransform; + if (parent && !parent.gameObject.scene.IsValid()) + parent = null; + Paste(parent); + } + + [MenuItem("Tools/Cross-Project Hierarchy/Paste At Scene Root", false, 3)] + public static void PasteAtRoot() { Paste(null); } + + [MenuItem("Tools/Cross-Project Hierarchy/Paste Under Selected %&v", true)] + [MenuItem("Tools/Cross-Project Hierarchy/Paste At Scene Root", true)] + private static bool ValidatePaste() + { + string buffer = EditorGUIUtility.systemCopyBuffer; + return !string.IsNullOrEmpty(buffer) && buffer.StartsWith(ClipboardHeader, StringComparison.Ordinal); + } + + private static bool HasSelectedAncestor(Transform child, HashSet selected) + { + for (var parent = child.parent; parent; parent = parent.parent) + if (selected.Contains(parent.gameObject)) + return true; + return false; + } + + private static string GetHierarchySortKey(Transform t) + { + var indices = new List(); + while (t) + { + indices.Add(t.GetSiblingIndex().ToString("D8")); + t = t.parent; + } + indices.Reverse(); + return string.Join("/", indices.ToArray()); + } + + private static void CaptureStructure(Transform transform, int parentId, + Package package, CaptureContext context) + { + var go = transform.gameObject; + int id = package.nodes.Count; + var node = new Node + { + id = id, + parentId = parentId, + name = go.name, + active = go.activeSelf, + tag = go.tag, + layer = go.layer, + layerName = LayerMask.LayerToName(go.layer), + staticFlags = (int)GameObjectUtility.GetStaticEditorFlags(go), + localPosition = transform.localPosition, + localRotation = transform.localRotation, + localScale = transform.localScale, + worldPosition = transform.position, + worldRotation = transform.rotation, + worldScale = transform.lossyScale, + hasRectTransform = transform is RectTransform + }; + + var rect = transform as RectTransform; + if (rect) + { + node.anchorMin = rect.anchorMin; + node.anchorMax = rect.anchorMax; + node.pivot = rect.pivot; + node.sizeDelta = rect.sizeDelta; + node.anchoredPosition = rect.anchoredPosition; + } + + package.nodes.Add(node); + context.nodeIds.Add(go, id); + context.orderedObjects.Add(go); + + var components = go.GetComponents(); + for (int i = 0; i < components.Length; ++i) + { + if (!components[i]) + continue; + context.componentRefs[components[i]] = new Reference + { + kind = "hierarchy", + nodeId = id, + componentIndex = i + }; + } + + for (int child = 0; child < transform.childCount; ++child) + CaptureStructure(transform.GetChild(child), id, package, context); + } + + private static void CaptureFields(Component component, Part part, CaptureContext context) + { + try + { + var so = new SerializedObject(component); + var iterator = so.GetIterator(); + bool hasMore = iterator.NextVisible(true); + string ignoredManagedRoot = null; + while (hasMore) + { + string path = iterator.propertyPath; + if (!string.IsNullOrEmpty(ignoredManagedRoot)) + { + if (path.StartsWith(ignoredManagedRoot + ".", StringComparison.Ordinal)) + { + hasMore = iterator.NextVisible(true); + continue; + } + ignoredManagedRoot = null; + } + + if (ShouldSkipProperty(path)) + { + hasMore = iterator.NextVisible(true); + continue; + } + + if (iterator.propertyType == SerializedPropertyType.ManagedReference) + { + // Polymorphic managed references are not portable across arbitrary assemblies. + ignoredManagedRoot = path; + hasMore = iterator.NextVisible(true); + continue; + } + + try + { + var field = ReadField(iterator, context); + if (field != null) + part.fields.Add(field); + } + catch (Exception) + { + // An unsupported native property should never abort hierarchy copying. + } + hasMore = iterator.NextVisible(true); + } + } + catch (Exception ex) + { + Debug.LogWarning("Cross-Project Hierarchy: Could not serialize " + component.GetType().Name + ": " + ex.Message); + } + } + + private static bool ShouldSkipProperty(string path) + { + return path == "m_Script" || path == "m_GameObject" || + path == "m_ObjectHideFlags" || path == "m_CorrespondingSourceObject" || + path == "m_PrefabInstance" || path == "m_PrefabAsset" || + path == "m_EditorClassIdentifier" || path == "m_RootOrder"; + } + + private static Field ReadField(SerializedProperty p, CaptureContext context) + { + var field = new Field { path = p.propertyPath, kind = p.propertyType.ToString() }; + if (p.isArray && p.propertyType == SerializedPropertyType.Generic) + { + field.kind = "PortableArraySize"; + field.integerValue = p.arraySize; + return field; + } + + switch (p.propertyType) + { + case SerializedPropertyType.Integer: + case SerializedPropertyType.LayerMask: + case SerializedPropertyType.Character: + field.integerValue = p.longValue; + break; + case SerializedPropertyType.Boolean: + field.boolValue = p.boolValue; + break; + case SerializedPropertyType.Float: + field.doubleValue = p.doubleValue; + break; + case SerializedPropertyType.String: + field.stringValue = p.stringValue; + break; + case SerializedPropertyType.Color: + field.color = p.colorValue; + break; + case SerializedPropertyType.ObjectReference: + field.reference = CaptureReference(p.objectReferenceValue, context); + break; + case SerializedPropertyType.ExposedReference: + field.reference = CaptureReference(p.exposedReferenceValue, context); + break; + case SerializedPropertyType.Enum: + field.integerValue = p.intValue; + int index = p.enumValueIndex; + var names = p.enumNames; + if (index >= 0 && index < names.Length) + field.enumName = names[index]; + break; + case SerializedPropertyType.Vector2: + field.vector2 = p.vector2Value; + break; + case SerializedPropertyType.Vector3: + field.vector3 = p.vector3Value; + break; + case SerializedPropertyType.Vector4: + field.vector4 = p.vector4Value; + break; + case SerializedPropertyType.Quaternion: + field.quaternion = p.quaternionValue; + break; + case SerializedPropertyType.Rect: + field.rect = p.rectValue; + break; + case SerializedPropertyType.Bounds: + field.bounds = p.boundsValue; + break; + case SerializedPropertyType.Vector2Int: + field.vector2Int = p.vector2IntValue; + break; + case SerializedPropertyType.Vector3Int: + field.vector3Int = p.vector3IntValue; + break; + case SerializedPropertyType.RectInt: + field.rectInt = p.rectIntValue; + break; + case SerializedPropertyType.BoundsInt: + field.boundsInt = p.boundsIntValue; + break; + case SerializedPropertyType.AnimationCurve: + field.curve = p.animationCurveValue; + break; + case SerializedPropertyType.Gradient: + // In Unity 2019.4, gradientValue is not a public API. + // It remains unchanged on the receiving side. + return null; + default: + // Generic structs are handled through their children. + // Fixed-size buffers, new Unity 7-only types, etc. are skipped. + return null; + } + return field; + } + + private static Reference CaptureReference(Object obj, CaptureContext context) + { + if (!obj) + return new Reference { kind = "null" }; + + var go = obj as GameObject; + int nodeId; + if (go && context.nodeIds.TryGetValue(go, out nodeId)) + return new Reference { kind = "hierarchy", nodeId = nodeId, componentIndex = -1 }; + + var component = obj as Component; + Reference sceneRef; + if (component && context.componentRefs.TryGetValue(component, out sceneRef)) + return sceneRef; + + string path = AssetDatabase.GetAssetPath(obj); + if (!string.IsNullOrEmpty(path)) + { + string guid; + long localId; + if (!AssetDatabase.TryGetGUIDAndLocalFileIdentifier(obj, out guid, out localId)) + { + guid = AssetDatabase.AssetPathToGUID(path); + localId = 0; + } + var type = obj.GetType(); + return new Reference + { + kind = "asset", + name = obj.name, + path = path, + guid = guid, + localFileId = localId, + typeFullName = type.FullName, + assemblyName = type.Assembly.GetName().Name + }; + } + + // Unity built-in mesh/materials/shaders sometimes have no asset path. + if (obj is Mesh || obj is Material || obj is Shader) + { + var type = obj.GetType(); + return new Reference + { + kind = "asset", + name = obj.name, + typeFullName = type.FullName, + assemblyName = type.Assembly.GetName().Name + }; + } + + return new Reference { kind = "external", name = obj.name }; + } + + private static void Paste(Transform targetParent) + { + string buffer = EditorGUIUtility.systemCopyBuffer; + if (string.IsNullOrEmpty(buffer) || !buffer.StartsWith(ClipboardHeader, StringComparison.Ordinal)) + { + Debug.LogWarning("Cross-Project Hierarchy: Clipboard has no hierarchy data. Copy in the other Unity Editor first."); + return; + } + + Package package; + try { package = JsonUtility.FromJson(buffer.Substring(ClipboardHeader.Length)); } + catch (Exception ex) + { + Debug.LogError("Cross-Project Hierarchy: Invalid clipboard JSON: " + ex.Message); + return; + } + if (package == null || package.version != FormatVersion || package.nodes == null || + package.nodes.Count == 0 || package.nodes.Count > MaximumObjects) + { + Debug.LogError("Cross-Project Hierarchy: Unsupported or invalid clipboard format."); + return; + } + + var context = new PasteContext(); + var createdRoots = new List(); + Undo.IncrementCurrentGroup(); + int undoGroup = Undo.GetCurrentGroup(); + Undo.SetCurrentGroupName("Paste Cross-Project Hierarchy"); + + try + { + // Pass 1: always recreate every GameObject and parent relationship. + foreach (var node in package.nodes) + { + if (context.nodes.ContainsKey(node.id)) + throw new InvalidOperationException("Duplicate node ID in clipboard data."); + + GameObject go = node.hasRectTransform + ? new GameObject(node.name, typeof(RectTransform)) + : new GameObject(node.name); + go.SetActive(false); + Undo.RegisterCreatedObjectUndo(go, "Paste Cross-Project Hierarchy"); + context.nodes.Add(node.id, go); + + Transform parent; + if (node.parentId < 0) + { + parent = targetParent; + createdRoots.Add(go); + } + else if (context.nodes.ContainsKey(node.parentId)) + parent = context.nodes[node.parentId].transform; + else + throw new InvalidOperationException("Invalid parent ID in clipboard data."); + + if (parent) + go.transform.SetParent(parent, false); + else if (SceneManager.GetActiveScene().IsValid() && + go.scene != SceneManager.GetActiveScene()) + SceneManager.MoveGameObjectToScene(go, SceneManager.GetActiveScene()); + + go.transform.localPosition = node.localPosition; + go.transform.localRotation = node.localRotation; + go.transform.localScale = node.localScale; + + // Pasting a source child at scene root should preserve its world pose. + // Under a selected target, preserve the original LOCAL pose instead. + if (node.parentId < 0 && !parent) + { + go.transform.position = node.worldPosition; + go.transform.rotation = node.worldRotation; + go.transform.localScale = node.worldScale; + } + + var rect = go.transform as RectTransform; + if (rect) + { + rect.anchorMin = node.anchorMin; + rect.anchorMax = node.anchorMax; + rect.pivot = node.pivot; + rect.sizeDelta = node.sizeDelta; + rect.anchoredPosition = node.anchoredPosition; + rect.localRotation = node.parentId < 0 && !parent + ? node.worldRotation : node.localRotation; + rect.localScale = node.parentId < 0 && !parent + ? node.worldScale : node.localScale; + } + + int targetLayer = string.IsNullOrEmpty(node.layerName) + ? (node.layer >= 0 && node.layer < 8 ? node.layer : 0) + : LayerMask.NameToLayer(node.layerName); + go.layer = targetLayer >= 0 ? targetLayer : 0; + if (!string.IsNullOrEmpty(node.tag)) + { + try { go.tag = node.tag; } + catch (UnityException) { /* Tag not defined in destination. */ } + } + try { GameObjectUtility.SetStaticEditorFlags(go, (StaticEditorFlags)node.staticFlags); } + catch (Exception) { /* Static flags differ between Unity versions. */ } + } + + // Pass 2: create all components BEFORE resolving scene references. + foreach (var node in package.nodes) + { + var go = context.nodes[node.id]; + var reserved = new HashSet(); + if (node.parts == null) + continue; + foreach (var part in node.parts) + { + if (part == null) + continue; + Component dest; + if (part.isTransform) + { + dest = go.transform; + } + else + { + var type = ResolveType(part.typeFullName, part.assemblyName); + if (type == null || !typeof(Component).IsAssignableFrom(type) || type.IsAbstract || + typeof(Transform).IsAssignableFrom(type)) + { + context.missingComponents++; + context.Warn("Missing component type: " + part.typeFullName); + continue; + } + dest = null; + foreach (var existing in go.GetComponents(type)) + { + if (existing && existing.GetType() == type && !reserved.Contains(existing)) + { + dest = existing; + break; + } + } + if (!dest) + { + try + { + dest = go.AddComponent(type); + context.componentsAdded++; + } + catch (Exception ex) + { + context.missingComponents++; + context.Warn("Could not add " + part.typeFullName + ": " + ex.Message); + continue; + } + } + } + reserved.Add(dest); + context.components[ComponentKey(node.id, part.componentIndex)] = dest; + } + } + + // Pass 3: apply serialized properties, including in-hierarchy links. + foreach (var node in package.nodes) + { + if (node.parts == null) + continue; + foreach (var part in node.parts) + { + if (part == null || part.isTransform) + continue; + Component dest; + if (!context.components.TryGetValue(ComponentKey(node.id, part.componentIndex), out dest)) + continue; + ApplyFields(dest, part.fields, context); + } + } + + // Pass 4: restore activeSelf AFTER all components are wired up. + // We also set it on inactive parents' children to preserve activeSelf. + foreach (var node in package.nodes) + context.nodes[node.id].SetActive(node.active); + + Selection.objects = createdRoots.Cast().ToArray(); + if (createdRoots.Count > 0) + EditorGUIUtility.PingObject(createdRoots[0]); + } + catch (Exception ex) + { + Debug.LogError("Cross-Project Hierarchy: Paste failed: " + ex); + // The created objects are still in the Undo group and can be undone. + } + finally + { + Undo.CollapseUndoOperations(undoGroup); + } + + Debug.Log(string.Format( + "Cross-Project Hierarchy: {0} GameObjects created. Components added: {1}. " + + "Missing component types: {2}. Unresolved references: {3}. Skipped fields: {4}. " + + "Source Unity: {5}. Target Unity: {6}.", + context.nodes.Count, context.componentsAdded, context.missingComponents, + context.missingReferences, context.skippedFields, + package.sourceUnityVersion, Application.unityVersion)); + foreach (var warning in context.warnings) + Debug.LogWarning("Cross-Project Hierarchy: " + warning); + } + + private static string ComponentKey(int id, int index) + { + return id.ToString() + ":" + index.ToString(); + } + + private static void ApplyFields(Component target, List fields, PasteContext context) + { + if (fields == null || fields.Count == 0) + return; + try + { + var so = new SerializedObject(target); + so.Update(); + + // Array lengths must be set from outer to inner before assigning elements. + var arrays = fields.Where(f => f.kind == "PortableArraySize") + .OrderBy(f => f.path.Length); + foreach (var field in arrays) + { + try + { + var prop = so.FindProperty(field.path); + if (prop != null && prop.isArray) + prop.arraySize = Mathf.Clamp((int)field.integerValue, 0, 100000); + } + catch (Exception) { context.skippedFields++; } + } + so.ApplyModifiedProperties(); + so.Update(); + + foreach (var field in fields) + { + if (field.kind == "PortableArraySize") + continue; + try + { + var prop = so.FindProperty(field.path); + if (prop == null || prop.propertyType.ToString() != field.kind) + { + context.skippedFields++; + continue; + } + WriteField(prop, field, context); + } + catch (Exception) + { + context.skippedFields++; + } + } + so.ApplyModifiedProperties(); + } + catch (Exception ex) + { + context.Warn("Could not restore " + target.GetType().Name + ": " + ex.Message); + } + } + + private static void WriteField(SerializedProperty prop, Field field, PasteContext context) + { + switch (prop.propertyType) + { + case SerializedPropertyType.Integer: + case SerializedPropertyType.LayerMask: + case SerializedPropertyType.Character: + prop.longValue = field.integerValue; + break; + case SerializedPropertyType.Boolean: + prop.boolValue = field.boolValue; + break; + case SerializedPropertyType.Float: + prop.doubleValue = field.doubleValue; + break; + case SerializedPropertyType.String: + prop.stringValue = field.stringValue; + break; + case SerializedPropertyType.Color: + prop.colorValue = field.color; + break; + case SerializedPropertyType.ObjectReference: + prop.objectReferenceValue = ResolveReference(field.reference, context); + break; + case SerializedPropertyType.ExposedReference: + prop.exposedReferenceValue = ResolveReference(field.reference, context); + break; + case SerializedPropertyType.Enum: + if (!string.IsNullOrEmpty(field.enumName)) + { + int index = Array.IndexOf(prop.enumNames, field.enumName); + if (index >= 0) + { + prop.enumValueIndex = index; + break; + } + } + prop.intValue = (int)field.integerValue; + break; + case SerializedPropertyType.Vector2: + prop.vector2Value = field.vector2; + break; + case SerializedPropertyType.Vector3: + prop.vector3Value = field.vector3; + break; + case SerializedPropertyType.Vector4: + prop.vector4Value = field.vector4; + break; + case SerializedPropertyType.Quaternion: + prop.quaternionValue = field.quaternion; + break; + case SerializedPropertyType.Rect: + prop.rectValue = field.rect; + break; + case SerializedPropertyType.Bounds: + prop.boundsValue = field.bounds; + break; + case SerializedPropertyType.Vector2Int: + prop.vector2IntValue = field.vector2Int; + break; + case SerializedPropertyType.Vector3Int: + prop.vector3IntValue = field.vector3Int; + break; + case SerializedPropertyType.RectInt: + prop.rectIntValue = field.rectInt; + break; + case SerializedPropertyType.BoundsInt: + prop.boundsIntValue = field.boundsInt; + break; + case SerializedPropertyType.AnimationCurve: + prop.animationCurveValue = field.curve; + break; + default: + context.skippedFields++; + break; + } + } + + private static Object ResolveReference(Reference reference, PasteContext context) + { + if (reference == null || reference.kind == "null") + return null; + if (reference.kind == "hierarchy") + { + Object obj = null; + if (reference.componentIndex < 0) + { + GameObject go; + if (context.nodes.TryGetValue(reference.nodeId, out go)) + obj = go; + } + else + { + Component part; + if (context.components.TryGetValue(ComponentKey(reference.nodeId, reference.componentIndex), out part)) + obj = part; + } + if (!obj) + context.missingReferences++; + return obj; + } + if (reference.kind != "asset") + { + context.missingReferences++; + return null; + } + + string key = (reference.guid ?? "") + "|" + reference.localFileId + "|" + + (reference.path ?? "") + "|" + (reference.name ?? "") + "|" + + (reference.typeFullName ?? ""); + Object cached; + if (context.assetCache.TryGetValue(key, out cached)) + return cached; + + Type type = ResolveType(reference.typeFullName, reference.assemblyName); + Object resolved = type == null ? null : FindAsset(reference, type); + context.assetCache[key] = resolved; + if (!resolved) + { + context.missingReferences++; + context.Warn("Asset not found: " + reference.name + " (" + reference.path + ")"); + } + return resolved; + } + + private static Object FindAsset(Reference reference, Type type) + { + // GUID is the best match when the source .meta file was transferred. + if (!string.IsNullOrEmpty(reference.guid)) + { + string path = AssetDatabase.GUIDToAssetPath(reference.guid); + var asset = FindAtPath(path, reference, type); + if (asset) + return asset; + } + + // Useful when assets were separately imported with different GUIDs. + if (!string.IsNullOrEmpty(reference.path)) + { + var asset = FindAtPath(reference.path, reference, type); + if (asset) + return asset; + } + + if (type == typeof(Shader)) + return Shader.Find(reference.name); + + if (type == typeof(Mesh) && IsBuiltinReference(reference)) + { + var mesh = FindBuiltinPrimitiveMesh(reference.name); + if (mesh) + return mesh; + } + + if (type == typeof(Material) && IsBuiltinReference(reference) && + (reference.name == "Default-Material" || reference.name == "Default Material")) + { + var material = AssetDatabase.GetBuiltinExtraResource("Default-Material.mat"); + if (material) + return material; + } + + if (!AllowUniqueAssetNameFallback || string.IsNullOrEmpty(reference.name)) + return null; + + // This fallback only accepts an exact, UNIQUE name and type match. + // Never arbitrarily bind a reference to a different asset. + string[] guids = AssetDatabase.FindAssets(reference.name + " t:" + type.Name); + Object onlyMatch = null; + foreach (string guid in guids) + { + string path = AssetDatabase.GUIDToAssetPath(guid); + if (string.IsNullOrEmpty(path)) + continue; + foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(path)) + { + if (!asset || !type.IsInstanceOfType(asset) || asset.name != reference.name) + continue; + if (onlyMatch && onlyMatch != asset) + return null; + onlyMatch = asset; + } + } + return onlyMatch; + } + + private static bool IsBuiltinReference(Reference reference) + { + return string.IsNullOrEmpty(reference.path) || + reference.path.IndexOf("unity_builtin_extra", StringComparison.OrdinalIgnoreCase) >= 0 || + reference.path.IndexOf("unity default resources", StringComparison.OrdinalIgnoreCase) >= 0; + } + + private static Object FindAtPath(string path, Reference reference, Type type) + { + if (string.IsNullOrEmpty(path)) + return null; + Object nameMatch = null; + Object idMatch = null; + try + { + var assets = AssetDatabase.LoadAllAssetsAtPath(path); + foreach (var asset in assets) + { + if (!asset || !type.IsInstanceOfType(asset)) + continue; + if (reference.localFileId != 0) + { + string guid; + long fileId; + if (AssetDatabase.TryGetGUIDAndLocalFileIdentifier(asset, out guid, out fileId) + && fileId == reference.localFileId && + (guid == reference.guid || asset.name == reference.name)) + idMatch = asset; + } + if (asset.name == reference.name) + nameMatch = asset; + } + if (idMatch) + return idMatch; + if (nameMatch) + return nameMatch; + if (assets.Length == 1 && assets[0] && type.IsInstanceOfType(assets[0]) && + (string.IsNullOrEmpty(reference.name) || assets[0].name == reference.name)) + return assets[0]; + } + catch (Exception) { /* Some built-in paths are not regular asset paths. */ } + return null; + } + + private static Mesh FindBuiltinPrimitiveMesh(string name) + { + PrimitiveType primitive; + switch (name) + { + case "Cube": primitive = PrimitiveType.Cube; break; + case "Sphere": primitive = PrimitiveType.Sphere; break; + case "Capsule": primitive = PrimitiveType.Capsule; break; + case "Cylinder": primitive = PrimitiveType.Cylinder; break; + case "Plane": primitive = PrimitiveType.Plane; break; + case "Quad": primitive = PrimitiveType.Quad; break; + default: return null; + } + + GameObject temp = null; + try + { + temp = GameObject.CreatePrimitive(primitive); + var filter = temp.GetComponent(); + return filter ? filter.sharedMesh : null; + } + finally + { + if (temp) + Object.DestroyImmediate(temp); + } + } + + private static Type ResolveType(string fullName, string assemblyName) + { + if (string.IsNullOrEmpty(fullName)) + return null; + if (!string.IsNullOrEmpty(assemblyName)) + { + var type = Type.GetType(fullName + ", " + assemblyName, false); + if (type != null) + return type; + } + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + if (!string.IsNullOrEmpty(assemblyName) && + assembly.GetName().Name != assemblyName) + continue; + var type = assembly.GetType(fullName, false); + if (type != null) + return type; + } + // Unity built-in type locations sometimes change between versions. + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + var type = assembly.GetType(fullName, false); + if (type != null) + return type; + } + return null; + } + } +} diff --git a/Assets/Scripts/Editor/Tools/FindWhatButtonCallsMyMethod.cs b/Assets/Scripts/Editor/Tools/FindWhatButtonCallsMyMethod.cs new file mode 100644 index 0000000..e67f45b --- /dev/null +++ b/Assets/Scripts/Editor/Tools/FindWhatButtonCallsMyMethod.cs @@ -0,0 +1,69 @@ +// prints out which buttons in current scene are referencing your given method + +using UnityEngine; +using UnityEngine.UI; +using UnityEditor; +using UnityEngine.Events; +using System.Reflection; + +namespace UnityLibrary +{ + public class FindWhatButtonCallsMyMethod : EditorWindow + { + private string methodName = "MyMethodHere"; + + [MenuItem("Tools/Find Buttons with Method")] + public static void ShowWindow() + { + GetWindow("FindWhatButtonCallsMyMethod"); + } + + private void OnGUI() + { + GUILayout.Label("Find Buttons that call Method", EditorStyles.boldLabel); + methodName = EditorGUILayout.TextField("Method Name:", methodName); + + if (GUILayout.Button("Find Buttons")) + { + FindButtonsWithMethod(); + } + } + + private void FindButtonsWithMethod() + { + Button[] allButtons = FindObjectsOfType