why dosent this trigger the else statement? pls help

public class RayTest : MonoBehaviour
{
void Update()
{

    if (Input.GetButtonDown("Fire1")) 
    {
        Vector3 mouseworld; 
        mouseworld = Camera.main.ScreenToWorldPoint(Input.mousePosition); 
    
        RaycastHit2D hit; 

        hit = Physics2D.Raycast(mouseworld, Vector2.zero); 

        if (hit.collider.name == "Ball") 
        {
            GameObject.Find("Gamecontroller").GetComponent<score>().Score++;
        }
        else
        {
            Debug.Log("why dosent this work?");
            GameObject.Find("Gamecontroller").GetComponent<score>().Score -= 1;
        }
    }
}

}

You said:

when i click something other than
“Ball”

but do you actually click something else or did you just click somewhere else? Because this line:

if (hit.collider.name == "Ball") 

would throw a null reference exception in case you don’t hit anything. That’s because when you did not hit any collider, hit.collider would be null so you can not read the name of something that doesn’t exist. If you look at the example shown in the documentation you should first check if you actually have a collider ot not. So try something like:

if (hit.collider != null && hit.collider.name == "Ball") 

However if this solves your problem you haven’t described your problem properly. If you get an error you should mention that error.

Script itself works fine, and else works if you click an object and ray collides with object which name is not Ball. In your case you just did not hit anything, and you don’t check that in your code. Instead try this:

public class RayTest : MonoBehaviour
{
    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {

            Vector3 mouseworld;
            mouseworld = Camera.main.ScreenToWorldPoint(Input.mousePosition);

            RaycastHit2D hit;
            hit = Physics2D.Raycast(mouseworld, Vector2.zero);

            if (hit.collider != null)
            {
                if (hit.collider.name == "Ball")
                {
                    Debug.Log("Hit the ball!");
                    //GameObject.Find("Gamecontroller").GetComponent<score>().Score++;
                }
                else
                {
                    Debug.Log("Hit something other than the Ball!");
                    //GameObject.Find("Gamecontroller").GetComponent<score>().Score -= 1;
                }
            }

            else
            {
                Debug.Log("Didn't hit anything!");
            }
        }
    }
}

when i click something other than “Ball” it dosen’t trigger the else statement

Maybe specifically requesting the name of the object will help?

hit.collider.gameObject.name == "Ball"

Also you are giving the Physics2D.Raycast a direction of 0,0 instead of something like Vector2.up (0,1).