Reputation: 63
I decided to try create a simple cookie clicker game as my first solo project with no tuts or courses, I managed to get to a point where I can click on my "Cookie" and it adds 1 to the cookieCounter however unity seems to think everything is my cookie...
Not sure if it's my code or something in unity set up wrong but I am sure someone here could point me in the right direction.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class cookieCounter : MonoBehaviour
{
public TextMeshProUGUI countText;
public GameObject Cookie;
private int count = 0;
private Rigidbody rb;
private string Object;
// Start is called before the first frame update
void Start()
{
count = 0;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0)) // On left click
{
Debug.Log(gameObject.name); //Returns the Object of which was clicked on
OnMouseOver();
countText.text = count.ToString("Cookies: 0"); // Updates the cookie counter on screen
Debug.Log(count); // Returns Final Count
}
}
private void OnMouseOver() // Looks at mouse and what it is hovering
{
Object = (gameObject.name); // Detects what the mouse is hovering over
if (Object == "Cookie") // Makes sure the object mouse is hovering is the "Cookie"
{
count++; // Adds 1 to the cookie counter.
}
}
}
Please ignore the inefficient code I haven't done this before.
Upvotes: 0
Views: 1070
Reputation: 141
I think you can use the function OnMouseDown() instead (Input.GetMouseButtonDown(0)). https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html
The difference is OnMouseDown will be called when you click on the object (the object must have a collider). Input.GetMouseButtonDown(0) will be called when you click everywhere on the screen.
Upvotes: 1
Reputation: 999
You check if the mouse is clicked and current object is "Cookie"
, but you don't check where the click happened. If Cookie
object shares same Update
/OnMouseOver
methods as in question code, it will increase count
no matter where the click was.
You can fix it by taking mouse position into consider. If Cookie is UI, you can let Button
class handle everything related to detecting mouse click(the easy way).
If Cookie is 2D SpriteRenderer
object(or 3D) then you can use EventSystem
(possibly already included in your project) and implement IPointerClickHandler
in Cookie class. You can find detailed solution in internet, like https://forum.unity.com/threads/solved-detecting-mouse-click-on-an-object-in-2d-game.478514/ .
Upvotes: 2