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.
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
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
I am trying to assign ScriptManager to ObjectManager, and used the line :
ObjectManager = GameObject.Find("ScriptManager");
I have checked multiple times to make sure "ScriptManager" is spelt correct, Ive even tried copy pasting the name straight from Unity.
I recieve this error when running:
"UnassignedReferenceException: The variable ObjectManager of Mining has not been assigned.
You probably need to assign the ObjectManager variable of the Mining script in the inspector.
UnityEngine.GameObject.GetComponent[T] () (at <3be1a7ff939c43f181c0a10b5a0189ac>:0)
Mining.Sell () (at Assets/Mining.cs:49)"
I sadly cant assign the variable straight from the inspector, because the object with the code attached is loaded using a Prefab.
here is the full code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Mining : MonoBehaviour
{
public GameObject ObjectManager;
public Text WorkerCountText;
public float MiningSpeed;
public float WorkersInMine;
public float MiningMultiplyer;
public Collider2D collider;
public GameObject DropDown;
private float WorkerCount;
private float MineWorth;
private float Cash;
// Start is called before the first frame update
void Start()
{
ObjectManager = GameObject.Find("ScriptManager");
collider = GetComponent<Collider2D>();
DropDown.SetActive(false);
}
// Update is called once per frame
void Update()
{
Cash = ObjectManager.GetComponent<GenerateItems>().Money;
WorkerCount = ObjectManager.GetComponent<GenerateItems>().Workers;
MineWorth = ObjectManager.GetComponent<GenerateItems>().MineCost;
WorkerCountText.text = "Workers:" + WorkerCount;
}
public void Sell()
{
ObjectManager.GetComponent<GenerateItems>().Money = Cash + MineWorth;
Object.Destroy (this);
}
}
I would change the way how you assign the ScriptManager to ObjectManager. The function Find() is not very reliable and in case if anything changes in hierarchy or in the name of the GameObject, the function will not find the desired GameObject.
There are multiple ways how you can assign the GameObject to the ObjectManager, including more reliable function FindObjectOfType(), or simply creating variable:
public GameObject objectManager;
and dragging your ObjectManager from the hierarchy into the inspector in the ScriptManager GameObject.
Note: If you want to use any function of the ObjectManager you would need to get that component in the Start function of the ScriptManager.
Try using Object.FindObjectOfType
https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html
I have discovered how to fix it!
For anyone wondering, the object this is attacked to is a prefab. And is only loaded once the player purchases the item. Meaning it is not loaded when Start() is executed. Moving the line into Sell() , Add() , and remove assigns it when the buttons are clicked. This fixed the error. Thank you to everyone who tried to help, I am now also using FindGameOBjectWithTag instead of Find to make sure it always works
I keep getting this error ( CS0106: The modifier 'private' is not valid for this item) and could use some help. I'm trying to make a random object generator for my game but since I am still a newbie coder I cannot seem to figure out how to fix this. Any help would be nice
Here is the code im using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class deployAsteroids : MonoBehaviour
{
public GameObject asteroidPrefab;
public float respawnTime = 1.0f;
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(screenBounds.x, screenBounds.y, Camera.main.transform.position.z));
StartCorountine(asteroidWave());
private void spawnEnemy()
{
GameObject a = Instantiate(asteroidPrefab) as GameObject;
a.transform.position = new Vector2(Random.Range(-screenBounds.x, screenBounds.x), screenBounds.y * -2);
}
IEnumerator astroidWave()
{
while (true)
{
yield return new WaitForSeconds(respawnTime);
spawnEnemy();
}
}
}
Anytime you get a compiler error the first thing you should consider is to lookup up the error code in a search engine. From CS0106 the rules are provided. The forth bullet point is clear on this.
Access modifiers are not allowed on a local function. Local functions are always private.
You have two options:
Move the method outside of the parent method (Start()). This is the typical scenario if it will be used in more than one place.
Remove the modifier private.
Try using the static modifier, and reading this. That could work, it worked for me when I got the same error in unity for a public void.
Also, consider moving your method out of Start(), like others have said.
I am new to coding and I've been trying to solve this problem.
I want to get the user's input from this input box and write it here. I managed to write this code
This is the first script
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SubmitButton : MonoBehaviour
{
object myObject = new Object();
public Button btnClick;
public InputField inputUser;
void Start()
{
btnClick.onClick.AddListener(GetInputOnClickHandler);
}
public void GetInputOnClickHandler()
{
Debug.Log("Input is " + inputUser.text);
inputUser.text = myObject.ToString();
}
}
And this is the second script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class txtScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Text txtMy = GameObject.Find("Canvas/Text").GetComponent<Text>();
txtMy.text = "Test" + ToString(SubmitButton.myObject);
}
// Update is called once per frame
void Update()
{
}
}
As you can see, I tried to acces myObject from SubmitButton but I got this error:
Assets\Scripts\txtScript.cs(12,53): error CS0122: 'SubmitButton.myObject' is inaccessible due to its protection level
I've tried to solve this but I can't manage to do it.
I used static modifiers/Getters & Setters but maybe I was doing something wrong.
It's probably easiest, at least while you're still familiarising yourself with coding, to simplify this down and just use one script which references the text input, submit button and text display.
This can be achieved by adding a line and adjusting a line in your first script SubmitButton, and removing or disabling the second txtScript (as it is not needed).
Declare an additional field for the displayText (this should reference the GameObject shown in your second screenshot)
public Text displayText;
Then on the submit action, directly update the displayText text to match the inputUser text
public void GetInputOnClickHandler()
{
Debug.Log("Input is " + inputUser.text);
displayText.text = inputUser.text;
}
Also derHugo mentions, it is not possible to create or meaningfully use the base Object class directly. Most objects you create & access via script in Unity are Components (e.g. Text, Button, Rigidbody, Renderer, etc.), Monobehaviour scripts which are attached to GameObjects (e.g. these scripts), or regular C# classes and structs which you have written to work in tandem with the former two (this last one being the only type you would usually explicitly instantiate using the new keyword).
I am new to C# and Unity and am having trouble finding a clear answer to my problem.
I am trying to create a simple TextMeshProUGUI text log buffer in a panel. The buffer itself works fine until I try to access it from another class - I believe because I am not creating the reference to the panel correctly.
Here is my code for the TextMeshProUGUI object collector:
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class TextLogControl : MonoBehaviour
{
public TextMeshProUGUI textPrefab; // Unity prefab
public List<TextMeshProUGUI> textItems = new List<TextMeshProUGUI>();
[SerializeField]
public int maxItems = 100;
public void LogText(string newTextString, Color newColor)
{
Instantiate(textPrefab, transform);
textPrefab.text = newTextString;
if (textItems.Count >= maxItems)
{
textItems.RemoveAt(0); // I should probably be destroying something, but that's another question
}
textPrefab.gameObject.SetActive(true);
textItems.Add(textPrefab);
}
// The above function works correctly if I write a test function within this same class
}
Here is the code for the class that is trying to access the LogText() function:
using System;
using UnityEngine;
public class World : MonoBehaviour
{
Color defaultColor = Color.black;
public TextLogControl textLog;
public void Init()
{
// I need to create a reference here somewhere, but nothing I am trying is working
textLog.LogText("Welcome - you made it!", defaultColor);
}
}
I am putting the TextLogControl script on the Unity GameObject that is holding the TMP objects, and that works on its own.
I thought that I was creating a reference to the holder GameObject by dragging it onto my World object in Unity as below, but I am still getting an NRE when I call World.Init(), which means that I'm doing something wrong, but I cannot figure out what.
I thought this would create the reference that is not being created
Edit: The error I'm receiving is
NullReferenceException: Object reference not set to an instance of an object
When trying to run World.Init() - specifically, textLog is null, even though I have got it dragged onto the appropriate spot in Unity (I believe).
As this is so long for comment,
A null reference means that it is trying to access something that doesn't exist. You either forgot to drag something in the editor, or you are a step ahead and have something un-commented that should still be commented. Your code is using something that isn't there. I recommend you to add this piece of code to your files to check either the error is coming from NullRefrence of class or the else code.
TextMeshProUGUIs = textPrefab.GetComponent<TextMeshProUGUI>();
if (TextMeshProUGUIs == null)
{
Debug.LogError("No TextMeshProUGUI component found.");
}
I am brand new at this, and I am having a few conundrums about this code that I put in. I followed a tutorial and I am still having some issues. All I want to do is move the object that I have this script attached to called Player, and the script is PlayerMovement.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public object Player(PlayerMovement) { // Identifier expected, and 'PlayerMovement.Player(PlayerMovement)' not all codes return a value
{
if (Input.GetKeyDown(KeyCode.W))
{
Transform.Translate(Vector3.forward * Time.deltaTime); //ERROR: An object reference is required for the non-static field, method or property 'Transform.Translate(vector3)
Debug.Log("W is pressed, and I should move forwards.");
}
if (Input.GetKeyDown(KeyCode.S))
{
Debug.Log("S is pressed, and I should move backwards.");
}
if (Input.GetKeyDown(KeyCode.A))
{
Debug.Log("A is pressed, and I should move left.");
}
if (Input.GetKeyDown(KeyCode.D))
{
Debug.Log("D is pressed, and I should move right.");
}
}
}
On line 22 I am getting 2 errors Identefier expected, and 'PlayerMovement.Player(PlayerMovement)' not all codes return a value.
On line 29 I am getting An object reference is required for the non-static field, method or property 'Transform.Translate(vector3)'
As I am brand new, I have been looking up answers for hours upon hours and every answer I come across whenever I google anything doesn't actually explain what I am doing wrong, or I just am not reading it properly.
The error on line 22 is caused by the function Player being of type object and you don't return an object in the method. If you replace:
public object Player(PlayerMovement)
with:
public void Player(PlayerMovement)
That error should go away or you could return an object but I am not sure what that would be.
First of all, as Spirit carp said. the program will expecting a return value so you should either return a value or change object to void
public object Player....
into a
public void Player....
and then the main problem is you are invoking the Transform.Translate instead of changing the actual transform of your gameObject.
as you said the PlayerMovement script is attached on your player gameobject so the goal is to make the gameobject change it's transform depends on the key input. try to invoke the transform itself not the class Transform. transform is the actual transform of the gameobject and Transform is the class so you are invoking an static method, instead try to use this.transform.Translate
this.transform.Translate(Vector3.forward * Time.deltaTime);
then the last thing make sure to call your method inside Update method to make it works