- Home /
Calling method once
Hello, i am beginner is c# language and i have question, how to call method just once.
The given code uses two methods OnMouseDown() and OnMouseUp). Basically when the mouse is clicked on the object, color changes to red, and when mouse is unclicked it goes back to the original color white. and it does as many times as you click on the object. However, what i want is a mouse click to work just once. so after the second, third or more click OnMouseDown() and OnMouseUp() should not be called.
What can i do to solve my problem? A googled a lot and looked up many answers but non of them answered this question specifically.
Any help/advise will be much appreciated. code is given below
using UnityEngine;
using UnityEngine.SceneManagement;
public class Box : MonoBehaviour
{
private void OnMouseDown()
{
GetComponent<SpriteRenderer>().color = Color.red;
}
private void OnMouseUp()
{
GetComponent<SpriteRenderer>().color = Color.white;
}
}
Answer by UnityedWeStand · Jun 24, 2020 at 06:54 AM
Easiest way is to create a variable that triggers after the first click
using UnityEngine;
using UnityEngine.SceneManagement;
public class Box : MonoBehaviour
{
private bool isClicked = false;
private void OnMouseDown()
{
if(!isClicked)
{
GetComponent<SpriteRenderer>().color = Color.red;
}
}
private void OnMouseUp()
{
if(!isClicked)
{
GetComponent<SpriteRenderer>().color = Color.white;
isClicked = true;
}
}
}
Answer by ShadyProductions · Jun 24, 2020 at 06:54 AM
using UnityEngine;
using UnityEngine.SceneManagement;
public class Box : MonoBehaviour
{
private bool hasClickedDown = false;
private bool hasClickedUp = false;
private void OnMouseDown()
{
if (hasClickedDown) return;
hasClickedDown = true;
GetComponent<SpriteRenderer>().color = Color.red;
}
private void OnMouseUp()
{
if (hasClickedUp) return;
hasClickedUp = true;
GetComponent<SpriteRenderer>().color = Color.white;
}
}