Raycast2D called multiple times, any help will be appreciated.

I have absolutely tried everything I could and I still can’t find a solution to this problem. I have a raycast that when the user presses a game object, a value should decrease by 1, but with my current code it decreases randomly between 2-3 times, here is the code:

using UnityEngine;
using System.Collections;

public class OnBallTouchScript : MonoBehaviour

{
    public GUIText ballText;
    public int ballValue;
    public int ballScore;
    public static bool canPlay = true;
    Component guitext1;
   
    void Update()
    {
        if (canPlay == true)
        {
            if (Input.GetMouseButtonDown (0))
            {
                Vector2 pos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
                RaycastHit2D hitInfo = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(pos), Vector2.zero);

               
                if (hitInfo == false)
                {
                }

                else if (hitInfo.collider.gameObject.name == gameObject.name)
                {
                    int ballLife = int.Parse(hitInfo.collider.gameObject.GetComponentInChildren <GUIText>().guiText.text);
                    ballLife -= 1;
                    hitInfo.collider.gameObject.GetComponentInChildren <GUIText>().guiText.text = ballLife.ToString();
               
                    if (ballLife < 1)
                    {
                        Destroy(hitInfo.collider.gameObject);
                        GameController.score += ballScore;
                    }
                }
            }
        }
    }
}

Any help would be greatly appreciated.

Not sure if this is going to help, but have you tried putting it into a function?

Thanks for the reply but I actually finally found a solution, I’m going to delete this post right now, I just needed to change line: else if (hitInfo.collider.gameObject.name == gameObject.name)
to:

else if (hitInfo.collider.gameObject == gameObject)

It makes sense, but I can’t believe it was that simple, and I wasted all this time complicating it.

Oh yeah, sorry I completely overlooked that XD

No problem mate, the fact that you suggested a solution means a lot, thanks :slight_smile: