- Home /
i am making an increment of one when user clicks a game object, trying to decrement the counter if the same game object is clicked again
i am making an increment of one when user clicks a game object, trying to decrement the counter if the same game object is clicked again. here is my code
void Update()
{
if( Input.GetMouseButtonDown(0) ) { Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
RaycastHit hit;
if( Physics.Raycast( ray, out hit, 100 ) )
{
if( hit.transform.gameObject.name == "answer" )
count++;
print(count);
}
}
}
Answer by Tibodo · Aug 08, 2016 at 07:54 PM
Yo,
Maybe you can use a Dictionnary (System.Collection.Generic)
Dictionnary<string, int>
also can store GameObject as id
Dictionnary<GameObject, int>
But if you can add a component on all wanted gameObjects, you might use the method "OnMouseOver" from MonoBehaviours
public class Foo : MonoBehaviour
{
[SerializeField]
private int foo = 0;
private void OnMouseOver()
{
if(Input.GetMouseDown(0))
{
if(foo == 0)
{
foo++;
}
else
{
foo--;
}
}
}
}
its is working only for one game object i.e when i click on a gamobject on first click its increment and on second its decrements. what i want to do is if i click on one game object it increment the value of foo=1, then i click on another gameobject it should increment to 2 but it remains 1.
Shortest way will be to set foo variable as static, that will be shared between all your GameObjects.
Or to keep your system, use generic collection hashset. It's work by keys, in short, you cannot have the same value in the collection. So in this case, when the raycast hit a GameObject you can add :
private HashSet hashSet = new HashSet();
then after the raycast ;
... if(hashSet.Contains(hit.transform.gameObject)) { count--; hashSet.Remove(hit.transform.gameObject); } else { count++; hashSet.Add(hit.transform.gameObject); } ...
Don't forget add "using System.Collection.Generic"