How do I make an integer go up when a game object is clicked?
using UnityEngine;
public class EggScript : MonoBehaviour
{
public int Progress = 0;
void OnMouseDown()
{
Progress += 1;
}
void Update()
{
Debug.Log (Progress);
}
}
Just wondering why this doesn't work. Am I doing something wrong? The Progress number goes into the console OK, it just doesn't increase when the game object it's attached to is clicked. I'm a bit of a beginner at this so idk what I'm doing really, just going off tutorials
Answer by Llama_w_2Ls · Aug 06, 2020 at 04:14 PM
When youre trying to click on gameobjects, the first thing youll need is a camera facing that object, then a raycast, that points to where your mouse clicks onto.
int Counter = 0;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0)) // if click detected
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //Create ray that points to mouse click
Vector3 Ray = ray.direction;
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, Ray, out hit))
{
if (hit.collider != null) // if i hit something
{
if (hit.collider.gameObject.name == "IncreaseCounterWhenClicked") // if i click on a gameobject called 'IncreaseCounterWhenClicked'
{
Counter += 1;
}
}
}
}
}
I know that the code may not be very beginners friendly but raycasting is a simple concept that many many tutorials cover. You can attach this script anywhere, preferably your main camera, and hopefully it should allow you to increase the counter value when you click on a gameobject in the scene. Hope it helps! @sizekk_
Your answer
Follow this Question
Related Questions
Make Jump Fish game 1 Answer
switch between 5 Ui icons by pressing a button 0 Answers
Shooting an instantiated missile the way a object is facing. 0 Answers
How do I make a scrollbar for the camera? 0 Answers
How to add more UI elements to Dropdown OptionData except default string and sprite values in Unity? 0 Answers