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;
}
}
}
}
when i click something other than "Ball" it dosen't trigger the else statement
Answer by Bunny83 · Feb 25, 2018 at 10:49 AM
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.
thanks it solved the problem, and yeah i proably should have included the error.
Answer by Lilius · Feb 25, 2018 at 10:51 AM
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!");
}
}
}
}
Answer by JasperDre · Feb 25, 2018 at 10:52 AM
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).
Your answer

Follow this Question
Related Questions
If statement being ignored 2 Answers
I have a specific problem with my trigger 0 Answers
Else section in if statement not executing? 0 Answers
Referencing a function in a C# script 1 Answer
Rotate a Vector2 around the Z axis on a mathematical level 1 Answer