- Home /
Unity doesn't recognize mouse clicks, C#
Good day,
I am trying to build a game that uses an inventory. The game works so that when player character clicks an object it disapperas from the map and adds the item to inventory.
However, I can't make Unity register the mouse clicks on the collider of items. The clicks in game have thus far given errors and with the current script the game doesn't even start. Help is now very welcome.
static public Dictionary<int, string> KeyDictionary = new Dictionary<int, string>
{
{0, "Golden Key"},
{1, "string.Empty"},
};
ItemClass1 ItemObject = new ItemClass1 ();
Inventory1 Inventory = new Inventory1 ();
public Ray mouseRay;
public RaycastHit rayHit;
void Start () {
KeyDictionary [0] = ItemObject.KeyItems.name;
}
void Update () {
//mouseRay = Camera.main.ScreenPointToRay (Input.mousePosition);
//Press the mouse putton
if (Input.GetMouseButtonDown (0))
{
//If the mouse touches the collider
if (Physics.Raycast (Camera.ScreenPointToRay (Input.mousePosition), out rayHit))
{
//Add item to inventory and destroy the object from the map
if (KeyDictionary [0] != string.Empty) {
Inventory1.inventoryNameDictionary [0] = KeyDictionary [0];
KeyDictionary [0] = string.Empty;
Destroy (gameObject);
Inventory.isKey = true;
}
}
}
if (Input.GetKeyDown (KeyCode.A)) {
//inventoryWindowToggle = false;
}
/*Physics.Raycast (mouseRay, out rayHit);
if (rayHit.collider.transform.tag == "Key")
{
inventoryWindowToggle = true;
}*/
}
}
The clicks in game have thus far given errors and with the current script the game doesn't even start
What kind of errors. What do you mean 'doesn't even start'?
if (Input.Get$$anonymous$$ouseButtonDown (0))
{
//At this point i would put in a....
Debug.Log("Pressed left click.");
//If the mouse touches the collider
...rest of your code
I try adding a debug.Log to your code and checking the console as you dont seem to have a way of checking if it is the mouseclick that is an issue or whether it actually something after that event. Do the debug shuffle and see whats occurring dude. Take care Gruffy
Answer by Tyyy1997 · Mar 23, 2014 at 07:05 PM
When you are using colliders to check mouse clicks, use
void OnMouseDown() {
}
Note that these colliders are easily blocked by other objects and colliders, so try bringing them as far forward as possible. With this method you will not have to use any raycasting method whatsoever.
Your answer
Follow this Question
Related Questions
Prevents a mouse click on interface to trigger a click to move script 1 Answer
Coroutine Chain of Events 1 Answer
Move on mouse click in Orthografic 30x45x0 angle 0 Answers
How to make object clickable when user enter collider ? 0 Answers
How do you check if the object that you want to destroy with a click is the right object? 1 Answer