# Functions

Functions are sets of code that can be run multiple times.

## **Parts of a Function**

Let's look at the code for creating and *calling* a function:

{% hint style="info" %}
Custom functions must be created outside of the Start() and Update() functions.
{% endhint %}

```csharp
// Creating a simple function called MakeRed
public void MakeRed() {
    gameObject.GetComponent<Renderer>().material.color = new Color(1.0F, 0, 0, 1.0F);
}
```

**public** - the [**scope**](#function-scope) of the function. It determines how it can be accessed.

**void** - the [**return type**](#function-type). In C#, this has to be stated and it limits the type of information returned and how it can be used. "Void" means the function is not providing information to be used as a value (here, the game object is being made red).

**MakeRed** - the function **name**. This is the representative phrase or word and can be anything that is not already used, but there are [some naming conventions and rules](#function-naming-conventions-and-rules) to follow to ensure it works.

**parentheses ( )** - where [**arguments**](#arguments) can be used to apply the function in specific ways.

**curly brackets { }** - hold the **code** to run when the function is *called.*

## Calling a Function

The code within the brackets of a function only runs when it's called in other code that is running.

Example calling MakeRed() within another function, including Start() or Update():

```csharp
// Make the current game object red
MakeRed();
```

## Function Scope

Scope determines how a function can be used. They are **private** by default, but adding the scope when creating a function helps developers read code quickly.

**Public** functions allow other scripts to access the function. You can make a function public by typing "public" before the return type when creating a custom function for a script.

**Private** functions are only accessible by the script they are created in.

To call a function in another script you can use the GetComponent<>() function with the name of the script within the angled brackets <>.

Example:

```csharp
// Accessing Example.cs also attached to this game object
gameObject.GetComponent<Example>().MakeRed();
```

## Function Type

Generally, functions *return* a value. Functions can be created to determine a value or object and then the function name can be used as a variable with that information. The type needs to be placed before the function name. The "return" keyword is then used at the end of the function's code to provide the value.

Example:

```csharp
public string SayYesOrNo()
    {
        string message;
        float randomNumber = Random.Range(0, 1.0F);

        if (randomNumber < 0.5)
        {
            message = "yes";
        }
        else
        {
            message = "no";
        }

        return message;
    }
```

Now, in another part of the code, this function can be called to have the string generated by SayYesOrNo():

```csharp
print("The answer is " + SayYesOrNo());
```

This is one of the messages that prints to the console:

![](https://3795241431-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M8XSUYVSlHMdPUNud-2%2F-M9pafHcopzBFXAfXmCJ%2F-M9pdI7MQjScEmJQIp_l%2Fimage.png?alt=media\&token=c05bc5b3-9aca-4caa-9ed5-8f0f6ee55a2f)

Please see the [list of types in the variable section](https://hopemoore.gitbook.io/unity-basics/variables#variable-types).

## Function Naming Conventions and Rules

Generally, function names can be almost anything. However, there are some strict rules and some good practices.

### **Strict Rules**

1. User-defined names cannot match keywords used within the script (i.e. bool, public, for, return, etc.).
2. Function names cannot match those within the same script with the same number of arguments.
3. Cannot start with a number.
4. No spaces.
5. No special characters.

### **Conventions and Best Practices**&#x20;

1. Use descriptive action names. Functions DO things and look similar to object constructors that create objects (such as Color), so having a verb in the name helps developers read the code.
2. Use "Pascal casing" for function names. This is where the first letter in each word in the function name is capitalized. Examples: MakeRed, PickRandomObject, DetermineDirection, etc. The Unity editor will convert this into friendly component labels within the Inspector Tab.

## Arguments

Arguments are values passed into the function to get different desired results based on those values.

Empty parentheses () after a function name means the function will perform the same functions each time.

To create a function that takes arguments, declare the temporary/local variable names within the parentheses, separated by commas. In C#, you must also put the type of variable you are declaring.

Example:

```csharp
public string SayYesOrNo(float posLevel, string currentMsg)
{
    string message = currentMsg;
    float randomNumber = Random.Range(0, 1.0F);

    if (randomNumber < posLevel)
    {
        message += " yes";
    }
    else
    {
       message += " no";
    }

    return message;
}
```

This does the same thing as the SayYesOrNo() function with no arguments, but takes into account a value for posLevel and adds to an already defined string.

To call a function with arguments, put the values or variables within the parentheses:

```csharp
string answerMessage = "The answer is";
float positivityLevel = 0.78F;

print(SayYesOrNo(positivityLevel, answerMessage));
```

The console will print something like:

![](https://3795241431-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M8XSUYVSlHMdPUNud-2%2F-M9pVt2Tn41TRPOgqJMt%2F-M9p_7rSdQylIHdT68l_%2Fimage.png?alt=media\&token=3c505859-e1ab-4ca5-940c-0031fc263c36)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hopemoore.gitbook.io/unity-basics/coding-basics/functions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
