Home > OS >  Error while trying to hide the cursor in Unity
Error while trying to hide the cursor in Unity

Time:01-26

So, I tried to hide the cursor in Unity using C# script. However, it returned this error message:

CS0117: 'Cursor' does not contain a definition for 'visible'

Here is the full code for reference

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

public class Cursor : MonoBehaviour
{
    public Vector3 worldPosition;
    public GameObject cursorobj;
    // Start is called before the first frame update
    void Start()
    {
        Cursor.visible = false;
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 mousePos = Input.mousePosition;
        mousePos.z = Camera.main.nearClipPlane;
        worldPosition = Camera.main.ScreenToWorldPoint(mousePos);
        cursorobj.transform.position = worldPosition;
    }
}

note: there was no error except for the line 12

I copied the exact code from the tutorial website, and also searched Google for similar situations. I couldn't find anything.

CodePudding user response:

The problem in your code is that you are defining a class with the name "Cursor" which is shadowing the Cursor on namespace UnityEngine

So your public class Cursor is missing a 'property' for the visibility, then the compiler cant find that and that is the reason of the error

public static bool visible;

but you mean for sure the Cursor on the UnityEngine namespace then you can specifically refer to it as

 UnityEngine.Cursor.visible = true;

in that case the compiler will not complain trying to tell you that your own "Cursor" has no static property for visibility

CodePudding user response:

Rename your class and the .cs file accordingly. I assume it's conflicting with Unitys "Cursor" class.

As an alternative, you could use an explicit call:

UnityEngine.Cursor.visible = false;

The Using UnityEngine; doesn't solve your problem as long as your class is called Cursor but the explicit call can solve this ambiguity.

  • Related