I want a function to return a certain value, else return false

In short, I notice that a lot of predefined functions in Unity (A simple game development platform I use) will either return a value (Such as a coordinate), or will return false if certain conditions are met. I attempted to do this myself, however the compiler is always looking for a transform as a return type, and will not allow me to return a boolean (because the function is declared to return a transform).

    Transform SelectObject() {
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    if (Physics.Raycast (ray, out hit, unitLayer))
        return hit.transform;
    else
        return false;
}

How do I return a certain data type, but also have my function return boolean (false) when the function 'fails' its task?

Upvotes: 0

Views: 93

Answers (1)

DRKblade
DRKblade

Reputation: 347

I haven't used Unity for a while, but I think you just need to do this:

Transform SelectObject() {
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    if (Physics.Raycast (ray, out hit, unitLayer))
        return hit.transform;
    else
        return null;
}

Unity have an utility that converts objects that derive from UnityEngine.Object to boolean: false if the object is null, true in other cases. This is a weird thing, but it actually worked for me.

I think you can implicitly convert Transform objects to boolean like this:

bool b = SelectObject();

Upvotes: 1

Related Questions