Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Resolved Simple cursor script with a heavy MS cost.

Discussion in 'Scripting' started by Dobalina, Jun 25, 2021.

  1. Dobalina

    Dobalina

    Joined:
    Sep 6, 2013
    Posts:
    94
    Hello! Script newb here... I have a question regarding the little bit of code shown below. It simply changes the ui texture of the cursor one mouse up or down. It functions as desired, though I noticed it takes 0.4-0.6 MS in the profiler. Am I wrong or is that pretty high? If so, is there a more efficient way? Maybe something that doesn't live in void Update? I don't know, I'm really a newb to scripting. Any suggestions is much welcomed!


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

    public class mouseCursor : MonoBehaviour
    {
    public Texture2D up;
    public Texture2D down;

    void Update()
    {
    if (Input.GetMouseButton(0))
    {
    Cursor.SetCursor(down, new Vector2(25, 25), CursorMode.Auto);
    } else Cursor.SetCursor(up, new Vector2(25, 25), CursorMode.Auto);
    }
    }
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,596
    So in your code, you're setting the Cursor image every frame, to down if it's down and up if it's up.

    I would not be setting the Cursor image every frame, instead only set it on the frames where the mouse state actually changes.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class mouseCursor : MonoBehaviour
    6. {
    7.     public Texture2D up;
    8.     public Texture2D down;
    9.  
    10.     void Update()
    11.     {
    12.         if (Input.GetMouseButtonDown(0))
    13.         {
    14.              Cursor.SetCursor(down, new Vector2(25, 25), CursorMode.Auto);
    15.         }
    16.         if (Input.GetMouseButtonUp(0))
    17.         {
    18.              Cursor.SetCursor(up, new Vector2(25, 25), CursorMode.Auto);
    19.         }
    20.     }
    21. }
     
    PraetorBlue likes this.
  3. Dobalina

    Dobalina

    Joined:
    Sep 6, 2013
    Posts:
    94
    Ah, I see what you're talking about in your example. Thanks a lot! :D
     
    RadRedPanda likes this.