Else Statement doesn't work in unity?

933 views Asked by At

Alright so here is my code. This should be really simple but it doesn't want to work with me for some reason. Raycast sends a ray from the mouse, if it hits an object with a tag, it assigns a number to a variable. If it doesn't hit an object, then it sets the variable as -99. For some reason mine is hanging on:

A. I don't hit the objects, it outputs -99 the first time but after that it hangs on getting assigned 4.

B.I hit the objects and it will work just fine. After I click OFF the objects it hangs on the variable from the object I just hit previously.

em.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameFunctions : MonoBehaviour {

int Hitnum = -99;
void Start () {
    }

    void Update () {

        if (Input.GetMouseButtonDown (0)) {
            objectCheck ();
        }

    }
    //end of UPDATE function



public void objectCheck () {
        RaycastHit hit; 
        Ray ray = camera.ScreenPointToRay (Input.mousePosition);
        if (Physics.Raycast (ray, out hit, 10000.0f)) {
            if (hit.collider.tag == "Box") {
                Hitnum = 1;
            } else if (hit.collider.tag == "Sphere") {
                Hitnum = 2;
            } else if (hit.collider.tag == "Pyramid") {
                Hitnum = 3;
            } else if (hit.collider.tag == "Trapezoid") {
                Hitnum = 4;
            } else {
                Hitnum = -99;
            }
        }
        Debug.Log (Hitnum);
    }
    //end of check

}

Thanks in advance. This is driving me nuts because it should be simple.

EDIT: posted full code this time, yes all of it. I should mention that there are no other objects with tags, it's just null space. This was supposed to be a very basic shape identifier for kids.

EDIT:EDIT: I expect it to put out -99 if you do not hit the object. Later I will probably do something with the numbers but right now I jest need to fix this.

1

There are 1 answers

2
Mike Smith On

Restarted unity, everything works fine now. Thanks. Looked through my settings to see what had changed. I earlier deleted the background that had a background tag on it. I guess unity decided that if there is not hit on raycast, it will get the object that it last hit?