I have a little confusion regardin of the use of void. It is said that void should be used when there is no return after the function had worked. But in this class, we use a void for declaring our Method/Function (StartGame & NextGuess), and I see some returns. In the StartGame Method/Function the variable max is assigned a new value which keeps until the end of the code; and the StartGame Method/Function the guess variable gets a new value.
Could somebody explain me what is the logic behind this (void does not return any value)?
Probably easiest to give you an example of the difference.
Let’s first use an example of a method with void as it’s return type. This indicates that the method will not return anything to the statement which called it;
using UnityEngine;
public class Example : MonoBehaviour
{
private void Start()
{
DisplayMessage();
}
private void DisplayMessage()
{
Debug.Log("Hi Abraham!");
}
}
in the above example the Start method executes and calls the DisplayMessage method, an output is made to the console. The DisplayMessage method does not return anything to the Start method.
Now, let’s try another example where we use a different return type for the method;
using UnityEngine;
public class Example : MonoBehaviour
{
private void Start()
{
bool result = MessageDisplayed();
if(result == true)
{
Debug.Log("Successfully displayed message to console");
}
}
private bool MessageDisplayed()
{
DisplayMessage();
return true;
}
private void DisplayMessage()
{
Debug.Log("Hi Abraham!");
}
}
Slightly noddy example, but, in this case the Start method creates a local variable result as type bool and stores the returned value from the MessageDisplayed method. MessageDisplayed calls DisplayMessage and simply returns a value of true. DisplayMessage just does what it did in the first example.
After MessageDisplayed has executed the variable result will now hold the value of true. We then test that variable in the if statement and, if it equals true (which we know it will), we output a further message to the console.
As another example;
using UnityEngine;
public class Example : MonoBehaviour
{
private void Start()
{
string fullName = GetFullName("Abraham", "Suero");
Debug.Log(fullName);
}
private string GetFullName(string forename, string surname)
{
string result = forename + " " + surname;
}
}
Again, a fairly noddy example, but it’s just to demonstrate the return types, in this case a string and how they can be used.