Anas
Anas

Reputation: 25

Can i call a function when If statement fails

void Update()
{
    bool playerInView = false;

    foreach (RaycastHit hit in eyes.hits)
    {
        if (hit.transform && hit.transform.tag == "Player")
        {
            playerInView = true;
        }
    }

    if (playerInView)
    {
        print ("Detected");
    }
    else
    {
        void OnGUI () {
            GUI.Box (new Rect (10, 10, 100, 90), "Loader Menu");
        }
    }
}

}

When i run in Unity it says void cannot be used in this context but when i remove function and just call a print then it works

Upvotes: 0

Views: 152

Answers (4)

Jordi Cruzado
Jordi Cruzado

Reputation: 885

Do it in this way:

bool playerInView = false;

void Update()
{
    playerInView = false;
    foreach (RaycastHit hit in eyes.hits)
    {
        if (hit.transform && hit.transform.tag == "Player")
        {
            playerInView = true;
        }
    }

    if (playerInView)
    {
        print ("Detected");
    }
}




void OnGUI()
{
    if (!playerInView)
    {
        GUI.Box (new Rect (10, 10, 100, 90), "Loader Menu");
    }
    ...
}

Upvotes: 1

Rohit Prakash
Rohit Prakash

Reputation: 1972

At first, try to write your question in an understandable context. anyway, you should write it like,

void Update()
    {
        bool playerInView = false;

        foreach (RaycastHit hit in eyes.hits)
        {
            if (hit.transform && hit.transform.tag == "Player")
            {
                playerInView = true;
            }
        }

        if (playerInView)
        {
            print("Detected");
        }
        else
        {
            OnGUI();
        }
    }
    void OnGUI()
    {
        GUI.Box(new Rect(10, 10, 100, 90), "Loader Menu");
    }

Upvotes: 0

Solano
Solano

Reputation: 550

Try:

if (playerInView)
{
    print ("Detected");
}
else
{
    GUI.Box (new Rect (10, 10, 100, 90), "Loader Menu");
}

Upvotes: 1

Codor
Codor

Reputation: 17605

The part

else
{
    void OnGUI () {
        GUI.Box (new Rect (10, 10, 100, 90), "Loader Menu");
    }
}

is not valid C# syntax; a function cannot be defined locally in this way. Perhaps you mean

else
{
    GUI.Box(new Rect (10, 10, 100, 90), "Loader Menu");
}

Upvotes: 2

Related Questions