Hi Matthew,
Welcome to our community.
In C#, the structure for a method signature goes like this:
accessModifier returnType MethodName (parameters)
By default, all C# methods without an access modifier are private
. void OnUserInput(string input)
was not declared with an (explicite) access modifier, so it is private
. private
means that this method can be accessed within the same object/instance only. However, Unity had got its own rules, so don’t worry about this.
void
is the return type. In our case, it indicates that the method returns nothing. The return;
instruction is optional for void
methods. Here are two examples:
void SayHello (string name)
{
print("Hello, " + name + "!");
return; // is optional
}
public int GetSum (int a, int b)
{
return (a + b);
}
void OnUserInput (string userInput)
{
print("The player typed: " + userInput);
}
The method name must be unambiguous. According to the C# coding convention, the preferred pattern for names is “DoSomething”.
Parameters in methods are optional. You can define them to make the method receive data. They act as local variables inside the method code block. The names for the parameters must be unambiguous. (I renamed the parameter of the OnUserInput method on purpose. You can test that in your code.)
When the method gets called, the expected data must be passed on. In the case of OnUserInput, it is a string. We do not call OnUserInput in our own script/object but Ben’s and Rick’s “secret” object does that during runtime when the player typed something.
If programmers followed the official C# coding convention, the On prefix indicates that the method was called from outside when a certain event happens. In the case of OnUserInput, the event is: The player typed something.
And that’s basically everything there is to know about method signatures in C#.
Did this clear it up for you?
See also:
- Microsoft C# Programming Guide: Methods