작업하다가 프레임 체커가 더 좋은게 있어서

남기는 용도로 저장(내 마음쏚~~~~ 져쟝~~~♡ ^^^^^^^^)

 

using UnityEngine;

using TMPro;
using System;

namespace MirzaBeig.VolumetricFogLite
{
    [ExecuteAlways]
    public class FPSDisplay : MonoBehaviour
    {
        public float fps { get; private set; }      // Frames per second (interval average).
        public float frameMS { get; private set; }  // Milliseconds per frame (interval average).

        GUIStyle style = new GUIStyle();

        public int size = 16;

        [Range(0.0f, 2.0f)]
        public float scale = 1.0f;

        [Space]

        public Vector2 position = new Vector2(16.0f, 16.0f);

        public enum Alignment { Left, Right }
        public Alignment alignment = Alignment.Left;

        [Space]

        public Color colour = Color.green;

        [Space]

        public float updateInterval = 0.5f;

        float elapsedIntervalTime;
        int intervalFrameCount;

        [Space]

        [Tooltip("Optional. Will render using GUI if not assigned.")]
        public TextMeshProUGUI textMesh;

        // Get average FPS and frame delta (ms) for current interval (so far, if called early).

        public float GetIntervalFPS()
        {
            // 1 / time.unscaledDeltaTime for same-frame results.
            // Same as above, but uses accumulated frameCount and deltaTime.

            return intervalFrameCount / elapsedIntervalTime;
        }
        public float GetIntervalFrameMS()
        {
            // Calculate average frame delta during interval (time / frames).
            // Same as Time.unscaledDeltaTime * 1000.0f, using accumulation.

            return (elapsedIntervalTime * 1000.0f) / intervalFrameCount;
        }

        void Update()
        {
            intervalFrameCount++;
            elapsedIntervalTime += Time.unscaledDeltaTime;

            if (elapsedIntervalTime >= updateInterval)
            {
                fps = GetIntervalFPS();
                frameMS = GetIntervalFrameMS();

                fps = (float)Math.Round(fps, 2);
                frameMS = (float)Math.Round(frameMS, 2);

                intervalFrameCount = 0;
                elapsedIntervalTime = 0.0f;
            }

            if (textMesh)
            {
                textMesh.text = GetFPSText();
            }
            else
            {
                style.fontSize = Mathf.RoundToInt(size * scale);
                style.fontStyle = FontStyle.Bold;
                style.normal.textColor = colour;
            }
        }

        string GetFPSText()
        {
            return $"FPS: {fps:.00} ({frameMS:.00} ms)";
        }

        void OnGUI()
        {
            string fpsText = GetFPSText();

            if (!textMesh)
            {
                Vector2 scaledPosition = position * scale;

                float x = scaledPosition.x;

                if (alignment == Alignment.Right)
                {
                    x = Screen.width - x - style.CalcSize(new GUIContent(fpsText)).x;
                }

                GUI.Label(new Rect(x, scaledPosition.y, 200, 100), fpsText, style);
            }
        }
    }
}

'Unity > Script' 카테고리의 다른 글

[Unity] Camare Position Move v1.0  (1) 2024.06.18
FrameChecker  (0) 2024.01.02

Unity URP 에서 기본으로 제공되던 Simple Camare Controler 가 있었지만,
어느순간 이 스크립트는 증발해버렸다 (잠수함패치 싫허효,,)

 

어디서 긁은거 + GPT를 활용하여 Unity Game View 에서 활용가능한 스크립트를 공유하고자 한다.

 

 

 

using UnityEngine;

public class FlyCamera : MonoBehaviour
{
    public Transform targetCamera; // 카메라 오브젝트를 할당할 프로퍼티

    public float mainSpeed = 1.0f; // regular speed
    public float shiftAdd = 250.0f; // multiplied by how long shift is held. Basically running
    public float maxShift = 1000.0f; // Maximum speed when holding shift
    public float camSens = 0.25f; // How sensitive it is with mouse
    public bool invertY = true;

    public float scrollWheelSens = 1f;
    public float verticalSpeed = 1.0f; // Q와 E키의 Y축 이동 속도

    private Vector3 lastMouse = new Vector3(255, 255, 255); // kind of in the middle of the screen, rather than at the top (play)
    private float totalRun = 1.0f;

    void Update()
    {
        if (targetCamera == null)
        {
            Debug.LogWarning("Target camera is not assigned.");
            return;
        }

        Camera cameraComponent = targetCamera.GetComponent<Camera>();
        if (cameraComponent == null)
        {
            Debug.LogWarning("No Camera component found on target.");
            return;
        }

        if (Input.GetMouseButton(1))
        {
            Cursor.visible = false;
            Cursor.lockState = CursorLockMode.Locked;

            var mouseMoveY = invertY ? -1 * Input.GetAxis("Mouse Y") : Input.GetAxis("Mouse Y");
            var mouseMoveX = Input.GetAxis("Mouse X");

            var mouseMove = new Vector3(mouseMoveY, mouseMoveX, 0) * camSens;
            targetCamera.eulerAngles = targetCamera.eulerAngles + mouseMove;
        }
        else
        {
            Cursor.visible = true;
            Cursor.lockState = CursorLockMode.None;
        }

        // Mouse camera angle done.

        // Keyboard commands
        Vector3 p = GetBaseInput();
        if (p.sqrMagnitude > 0)
        { // only move while a direction key is pressed
            if (Input.GetKey(KeyCode.LeftShift))
            {
                totalRun += Time.deltaTime;
                p = p * totalRun * shiftAdd;
                p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
                p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
                p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
            }
            else
            {
                totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
                p = p * mainSpeed;
            }

            p = p * Time.deltaTime;
            Vector3 newPosition = targetCamera.position;
            if (Input.GetKey(KeyCode.Space))
            { // If player wants to move on X and Z axis only
                targetCamera.Translate(p);
                newPosition.x = targetCamera.position.x;
                newPosition.z = targetCamera.position.z;
                targetCamera.position = newPosition;
            }
            else
            {
                targetCamera.Translate(p);
            }
        }

        // Q and E key for vertical movement
        if (Input.GetKey(KeyCode.Q))
        {
            targetCamera.position += Vector3.down * mainSpeed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.E))
        {
            targetCamera.position += Vector3.up * mainSpeed * Time.deltaTime;
        }

        var scroll = Input.GetAxis("Mouse ScrollWheel");
        mainSpeed += scroll * scrollWheelSens;

        // If the camera is orthographic, adjust the orthographic size with W and S keys
        if (cameraComponent.orthographic)
        {
            if (Input.GetKey(KeyCode.W))
            {
                cameraComponent.orthographicSize -= mainSpeed * Time.deltaTime;
            }
            if (Input.GetKey(KeyCode.S))
            {
                cameraComponent.orthographicSize += mainSpeed * Time.deltaTime;
            }

            // Clamp the orthographic size to prevent it from getting too small or negative
            cameraComponent.orthographicSize = Mathf.Clamp(cameraComponent.orthographicSize, 0.1f, 100f);
        }
    }

    private Vector3 GetBaseInput()
    { // returns the basic values, if it's 0 then it's not active.
        Vector3 p_Velocity = new Vector3();
        if (Input.GetKey(KeyCode.W))
        {
            p_Velocity += new Vector3(0, 0, 1);
        }
        if (Input.GetKey(KeyCode.S))
        {
            p_Velocity += new Vector3(0, 0, -1);
        }
        if (Input.GetKey(KeyCode.A))
        {
            p_Velocity += new Vector3(-1, 0, 0);
        }
        if (Input.GetKey(KeyCode.D))
        {
            p_Velocity += new Vector3(1, 0, 0);
        }
        return p_Velocity;
    }
}

'Unity > Script' 카테고리의 다른 글

[Unity] Frame Checker On Editor  (0) 2024.06.18
FrameChecker  (0) 2024.01.02

Unity Game Viewer에서 프레임을 체크할 수 있는 코드이다.

단점으로는 실제 빌드를 하였을때와 에디터 상에서 프레임의 차이가 발생되는 문제가 있으며,

단순하게 에디터 상에서 확인하기에는 이만한 친구가 없다.

* 해당 코드의 경우 구글링을 통해서 습득한 코드이기 때문에 최초 작성자는 알 수 없다.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FrameChecker : MonoBehaviour
{
    [Range(1, 200)]
    public int fFont_Size;
    [Range(0, 1080)]
    public float xPos;
    [Range(0, 2400)]
    public float yPos;
    [Range(0, 1)]
    public float Red, Green, Blue;

    float deltaTime = 0.0f;

    private void Start()
    {
       
    }

    void Update()
    {
        deltaTime += (Time.unscaledDeltaTime - deltaTime) * 0.1f;
    }

    void OnGUI()
    {
        int w = Screen.width, h = Screen.height;

        GUIStyle style = new GUIStyle();

        Rect rect = new Rect(xPos, yPos, w / 2, h * 2 / 100);
        style.alignment = TextAnchor.UpperLeft;
        style.fontSize = h * 2 / fFont_Size;
        style.normal.textColor = new Color(Red, Green, Blue, 1.0f);
        float msec = deltaTime * 1000.0f;
        float fps = 1.0f / deltaTime;
        string text = string.Format("{0:0.0} ms ({1:0.} fps)", msec, fps);
        GUI.Label(rect, text, style);
    }
}

'Unity > Script' 카테고리의 다른 글

[Unity] Frame Checker On Editor  (0) 2024.06.18
[Unity] Camare Position Move v1.0  (1) 2024.06.18

+ Recent posts