Unity Basics
  • Welcome
  • Getting Started with Unity Software
  • Helpful Shortcuts
  • The Unity Software Interface
    • The Default Interface
    • The Windows (Tabs)
      • Hierarchy Window
      • Scene Window
      • Project Window
      • Inspector Window
      • Game Window
      • Console Window
    • Other Layouts
      • Create a Custom Layout
  • Create
    • Creating Game Objects
      • 3D Primitives
      • Creating Game Objects in the Editor
      • Spawning Objects
      • Unhiding/Hiding Objects During Gameplay
      • Parenting
    • Creating Assets
    • Creating Components and Scripts
      • Adding Components in the Inspector
      • Creating Custom Components and Scripts
    • Creating Prefabs
  • Select and Update
    • General Selection
    • Search and Focus
    • Updating Game Objects
      • Updating Game Objects in the Editor
      • Updating Prefabs
    • Updating Assets
    • Updating Components
      • Update Components in the Inspector
      • Accessing Components Through Scripts
  • Delete
    • Deleting Game Objects
      • Deleting and Disabling Objects in the Editor
      • Using the Destroy() Function
    • Deleting Components and Scripts
      • Disabling and Removing Components in the Editor
      • Disabling and Removing Components During Gameplay
  • Translate, Rotate, and Scale
    • Intro to Transforms
    • Handy Transform Shortcuts
    • Translate
      • Positioning Game Objects in the Editor
      • Updating Position Through Script Code
      • Using the Transform.Translate() Function
    • Rotate
      • Rotating Game Objects in the Editor
      • Updating Rotation Through Script Code
      • Using the Transform.Rotate() Function
    • Scale
      • Resizing/Scaling Objects in the Editor
      • Updating Scale Through Script Code
    • Controlling Speed
    • Common Issues with Transforms
  • Materials
    • Material Basics
      • Creating and Applying Materials
      • Accessing Materials Through Code
  • Physics
    • Physics Basics
    • Colliders and Triggers
      • Collider Component Overview
      • Accessing Colliders Through Scripts
      • Common Issues: Colliders and Triggers
    • Rigidbody Component
      • Rigidbody Component Overview
      • Accessing the Rigidbody Component Through Scripts
      • Common Issues: Rigidbody Components
    • Common Issues: Physics and Velocity
  • Interaction
    • Interaction Basics
    • Keyboard Controls
    • Mouse Controls
  • Coding Basics
    • Intro to Scripts
    • Variables
    • Conditionals (If / Then / Else)
    • Arrays
    • Loops
    • Functions
Powered by GitBook
On this page
  • Parts of a Function
  • Calling a Function
  • Function Scope
  • Function Type
  • Function Naming Conventions and Rules
  • Strict Rules
  • Conventions and Best Practices
  • Arguments

Was this helpful?

  1. Coding Basics

Functions

PreviousLoops

Last updated 4 years ago

Was this helpful?

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:

Custom functions must be created outside of the Start() and Update() functions.

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

public - the of the function. It determines how it can be accessed.

void - the . 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 to follow to ensure it works.

parentheses ( ) - where 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():

// 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:

// 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:

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():

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

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

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

  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:

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:

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

print(SayYesOrNo(positivityLevel, answerMessage));

The console will print something like:

Please see the .

scope
return type
some naming conventions and rules
arguments
list of types in the variable section