Unity Basics Course: Trying Out Unity

Unity is a powerful platform widely used for game development and real-time 3D content creation. In this course, you will learn the basic concepts of Unity, how to install the program, and how to create a simple project. Unity offers various tools and features to make it easy for users of all levels to access and learn.

1. What is Unity?

Unity is a cross-platform game engine that was first released in 2005 and has gained great popularity ever since. Unity supports both 2D and 3D game development and can be deployed across various platforms (PC, mobile, console, etc.). Its main features include powerful graphics rendering, a physics engine, and a user-friendly editor.

1.1 Features of Unity

  • Cross-platform support: Can be deployed to various platforms with a single development effort.
  • User-friendly interface: Intuitive UI and drag-and-drop functionality.
  • Strong community: Supported by extensive resources, tutorials, and forums.
  • Scalability and flexibility: Functionalities can be extended through various plugins and assets.
  • Free and paid versions: Offers a free version suitable for individuals or small projects.

2. Installing Unity

To use Unity, you first need to install it. Here are the steps to install:

2.1 Installing Unity Hub

Unity Hub is a tool used to manage the Unity Editor and projects. Follow these steps to install:

  1. Visit the official Unity website to download Unity Hub.
  2. Run the downloaded file to complete the installation.

2.2 Installing Unity Editor

Install the Unity Editor through Unity Hub:

  1. Run Unity Hub and go to the “Install” tab.
  2. Click the “Install New” button.
  3. Select the desired version of Unity and click “Next”.
  4. Select any necessary additional modules (e.g., Android Build Support) and complete the installation.

3. Creating Your First Project

Once the installation is complete, let’s create your first project:

3.1 Creating a New Project

  1. Navigate to the “Projects” tab in Unity Hub.
  2. Click the “New” button.
  3. Set the project name and save path, select a template, and then click the “Create” button.

3.2 Introduction to the Editor Interface

When you create a project, the Unity Editor opens. The editor interface consists of the following main elements:

  • Scene View: Shows the 3D space that composes the current scene.
  • Game View: Provides a preview of what the final game will look like when executed.
  • Hierarchy Panel: Lists all objects present in the current scene.
  • Inspector Panel: Allows you to adjust the properties of selected objects.
  • Project Panel: Manages all assets in the project.

4. Placing Objects

Now, let’s place your first object in the scene.

4.1 Adding a Basic Object

  1. Right-click in the Scene View and select “3D Object” > “Cube”.
  2. The cube is added to the scene and also appears in the Hierarchy Panel.
  3. You can adjust the cube’s position, rotation, and scale in the Inspector Panel.

5. Adding Scripts

In Unity, you can add functionality to objects by writing scripts in C#. Let’s write a simple script.

5.1 Creating a Script

  1. Right-click in the Project Panel and select “Create” > “C# Script”.
  2. Name the script and double-click to open it in Visual Studio or your IDE.

5.2 Writing a Basic Script

public class CubeRotation : MonoBehaviour
{
    void Update()
    {
        transform.Rotate(new Vector3(0, 1, 0) * Time.deltaTime * 50);
    }
}

The above code sets the cube to rotate around the y-axis every frame.

5.3 Applying the Script

  1. Drag the created script onto the cube object in the scene to apply it.
  2. Press the play button in the Game View to confirm that the cube is rotating.

6. Creating a Simple Game

Now, let’s create a simple game. The goal is for the cube’s color to change when the player clicks on it.

6.1 Writing a Color Change Script

using UnityEngine;

public class CubeColorChange : MonoBehaviour
{
    void OnMouseDown()
    {
        GetComponent().material.color = Random.ColorHSV();
    }
}

The script above sets the cube to change to a random color each time it is clicked.

6.2 Applying the Script

  1. Write the above script in a new C# script file and drag it onto the cube to apply it.
  2. Click the play button in the Game View again and click the cube. The color will change.

7. Adding UI

Let’s add UI to the game to display information to the user.

7.1 Creating a UI Canvas

  1. Right-click in the Hierarchy Panel and select “UI” > “Canvas” to create a canvas.
  2. Add “Text” under the canvas to enter the game title or instructions.

7.2 Styling the UI

You can change font size, color, etc., in the Inspector Panel. Additionally, you can adjust the position and alignment to arrange it nicely.

8. Building and Deploying

Once game development is complete, you can build the outcome for deployment. Let’s move on to the next steps.

8.1 Setting Up Build

  1. Select “File” > “Build Settings” from the top menu.
  2. Select the desired platform and click the “Switch Platform” button.
  3. Click the “Build” button to create the executable file.

8.2 Deployment

The completed game can be deployed according to the platform. For instance, for PC, you distribute the executable file, and for mobile, you package it as an APK file for distribution.

9. Conclusion

In this course, we learned basic concepts of Unity and how to create a simple game. Unity is a very powerful tool, and continuous learning is required to master more complex features and techniques. Utilize various tutorials and resources to explore more functionalities.

10. References

Thank you for reading the Unity course on this blog! We support your Unity learning journey.

Basic Unity Course: Structure of Functions

Hello! In this course, we will take an in-depth look at ‘functions’, which are a crucial element when writing code in Unity. Functions are a core concept that enhances code reusability and readability, and they are essential to understand in game development.

1. What is a Function?

A function is a block of code that performs a specific task or operation. A function takes input values, processes them, and then returns output values. By defining tasks that need to be executed repeatedly as functions, code duplication is reduced, and maintenance becomes easier.

2. Basic Structure of a Function

In Unity, functions are written in C#. The basic structure of a function is as follows:


returnType functionName(parameterType parameterName)
{
    // implementation code
    return value; // if it is a return type function
}

2.1 Return Type

The return type of a function is the data type of the value that the function returns as a result. For example, there can be various data types such as int, float, string, etc. If a function does not return a value, void is used as the return type.

2.2 Function Name

The function name is the identifier used to call the function. Function names can consist of letters, numbers, and underscores (_), with the important note that they cannot start with a number. Generally, it is advisable to name the function using nouns or verbs that describe its functionality.

2.3 Parameters

Parameters are the input values passed to a function. Parameters consist of a type and a name. By using parameters when creating a function, values can be received from outside.

3. Function Example

Here, we will create a simple function. The following is an example of a function that adds two numbers.


public int AddNumbers(int a, int b)
{
    return a + b;
}

In the above code, a function named AddNumbers is defined. This function takes two integers, a and b, as input and returns their sum.

4. Function Call

To call a defined function, use the function name followed by parentheses, and pass arguments if necessary. Below is an example of calling the previously defined AddNumbers function:


int result = AddNumbers(5, 10);
Debug.Log(result); // prints 15 to the console

5. Built-in Functions and User-defined Functions

Unity provides many built-in functions. These functions are generally included in scripts that inherit from the MonoBehaviour class and provide various functionalities such as game object lifecycle methods and physical interaction methods. For example, Start(), Update(), etc.

User-defined functions are defined and used by developers. They write code to perform specific functions tailored to their tasks. These functions can be defined freely as per the developer’s requirements.

6. Variable Arguments in Functions

Variable arguments are useful when the number of parameters is not fixed. By writing the params keyword before the function parameters, variable arguments can be created. For example:


public void PrintNumbers(params int[] numbers)
{
    foreach (int number in numbers)
    {
        Debug.Log(number);
    }
}

The above function can print all integers regardless of the number passed during the call. When calling the function:


PrintNumbers(1, 2, 3, 4, 5);

7. Recursive Functions

A recursive function is a function that calls itself. This method is useful for solving problems iteratively, but must have an exit condition to avoid infinite calls. For example:


public int Factorial(int n)
{
    if (n <= 1)
        return 1;
    return n * Factorial(n - 1);
}

The above Factorial function calculates the factorial of a given number recursively.

8. Function Overloading

Function overloading is a feature that allows multiple functions with the same name to be defined but distinguished by the type or number of parameters. For example:


public int Add(int a, int b)
{
    return a + b;
}

public float Add(float a, float b)
{
    return a + b;
}

In the above example, the function Add is defined with two parameters that add integers and floats respectively.

9. Access Modifiers for Functions

Functions can be set with various access modifiers. The most commonly used access modifiers are public, private, protected, etc. Each access modifier controls the visibility of the function, determining whether it can be accessed by other scripts.

10. Conclusion

In this course, we have explored the structure and basic usage of functions in Unity in detail. Functions are critical elements that control the behavior of the game and keep the code clean. Understanding functions will enable more efficient game development.

If you would like more information, please refer to the official Unity documentation, forums, and various online courses. In the next session, we will cover advanced techniques related to functions. Thank you!

Unity Basics Course: Implementing UI Functions and Button Clicks

Unity is a powerful game engine that allows the creation of various games and interactive content. In this tutorial, we will explore how to use Unity’s UI system to implement a user interface and add button click functionality.

1. Overview of the Unity UI System

Unity’s UI system provides various elements that allow users to interact with the game. UI elements include text, buttons, images, sliders, and input fields. These UI elements significantly enhance the user experience of the game, helping players to understand and manipulate the game more easily.

2. Adding UI Elements

Let’s learn how to add UI elements in Unity. Below are the basic steps to create a button.

2.1. Creating a New UI Canvas

  • Select GameObject > UI > Canvas from the top menu of the Unity Editor to create a new canvas.
  • Once the canvas is created, it will automatically appear in the Scene view. The canvas acts as the parent for all UI elements.

2.2. Adding a Button

  • With the newly created canvas selected, choose GameObject > UI > Button to add a button.
  • Once the button is created inside the canvas, you can adjust its properties in the Inspector window.

3. Setting Button Properties

You can select the button and set the following properties in the Inspector window.

3.1. Changing Button Text

  • The button displays the text “Button” by default. To change this, select the Text object that is a child of the button.
  • In the Inspector window, find the Text component and change it to the desired text.

3.2. Changing Button Style

If you want to change the style of the button, use the button’s Image component. You can modify the background color, image, etc., to attract the user’s attention.

4. Adding Button Click Events

To perform a specific action when the button is clicked, you need to write a script. Below is how to add a button click event.

4.1. Creating a Script

  • Right-click in the Project view and select Create > C# Script to create a new script and name it ButtonClickHandler.
  • Double-click the created script to open it in Visual Studio or your preferred code editor for editing.

4.2. Writing the Script


using UnityEngine;
using UnityEngine.UI;

public class ButtonClickHandler : MonoBehaviour
{
    // Method called when the button is clicked
    public void OnButtonClick()
    {
        Debug.Log("The button has been clicked!");
        // Add actions to perform on button click here
    }
}

4.3. Connecting the Script to the Button

  • Select the button, and in the Inspector window, find the Button (Script) component.
  • Locate the On Click () event section and click the + button to add an event.
  • After adding the event, drag and drop the game object with the ButtonClickHandler script into the None (Object) section.
  • Select ButtonClickHandler > OnButtonClick from the dropdown menu.

5. Testing the Execution

Now that all settings are complete, click the play button at the top of the Unity Editor to run the game and try clicking the button. You will see a message “The button has been clicked!” in the console.

6. Additional UI Features

In addition to button functionality, you can add various UI elements. For example, you can add sliders, toggle buttons, and input fields to create a more complex user interface.

6.1. Adding a Slider

  • Select GameObject > UI > Slider to add a slider.
  • Adjust the properties of the slider to set the range of values, allowing users to select a value.

6.2. Adding an Input Field

  • Select GameObject > UI > Input Field to add an input field.
  • This is a scene element where users can input text. Manipulating the text in the input field helps users enter accurate data.

7. Summary

In this tutorial, we learned how to implement UI elements in Unity and add button click events. By utilizing Unity’s UI functionalities, you can increase user interaction and enhance the overall experience of the game. You can add more complex features to improve the user interface, and after solidifying your foundations with this tutorial, you can further explore more in-depth development.

8. Next Steps

Now that you have completed the basic tutorial, you should be ready to learn about more complex UI elements, animations, and event systems. Continue your learning through Unity’s official documentation and various tutorials.

This concludes our tutorial on implementing Unity UI functionality and button clicking. If you have questions or feedback, please leave a comment!

Unity Basic Course: C# Strings (string)

In C#, strings are one of the most fundamental data types used for storing text. When developing games in Unity, strings are essential in various elements such as character names, dialogue, team names, and more. This tutorial will provide an in-depth explanation of the string type in C# and introduce how to use it in Unity.

What is a String?

A string is a collection of characters, represented by wrapping it in ‘single quotes’ or ‘double quotes’. In C#, a string is an instance of the System.String class. Strings are immutable data types, meaning once a string is created, it cannot be changed. Instead, when modification is needed, a new string is created and returned.

Declaring and Initializing Strings

There are several ways to declare and initialize a string. The most basic method is as follows:

string myString = "Hello, Unity!";

Here, myString is a string variable that stores the text “Hello, Unity!”.

Initializing Strings in Various Ways

Let’s look at different methods to initialize strings.

string emptyString = ""; // An empty string
string anotherString = new string('A', 10); // A string with the character 'A' repeated 10 times

String Operations

C# provides various methods for handling strings. The simplest way to concatenate strings is by using the plus (+) operator.

string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; // "John Doe"

String.Format Method

To create more complex strings, you can use the String.Format method, which formats the values given as arguments into a string.

int score = 100;
string message = String.Format("Your score is {0}.", score); // "Your score is 100."

String Interpolation

Since C# 6.0, you can use string interpolation, which allows you to use variables directly within strings.

string message = $"Your score is {score}."; // "Your score is 100."

String Methods

The String class in C# provides various methods for working with strings. Here, we will look at some commonly used methods.

String Length

int length = myString.Length; // Returns the length of the string.

String Search

To check if a specific character is included in a string, you can use the Contains method.

bool containsHello = myString.Contains("Hello"); // true

Substring

You can extract a part of a string using the Substring method.

string sub = myString.Substring(7, 5); // "Unity"

String Split

If you want to split a string by a specific delimiter, you can use the Split method.

string[] words = "Unity, C#, String".Split(','); // ["Unity", " C#", " String"]

Changing Case of Strings

To convert all characters in a string to uppercase or lowercase, you can use the ToUpper and ToLower methods.

string upper = myString.ToUpper(); // "HELLO, UNITY!"
string lower = myString.ToLower(); // "hello, unity!"

Using Strings in Unity

In Unity, strings are needed in various places. For example, they can be used in UI text, log messages, dialogue systems, and more. Below are some examples of how to utilize strings in Unity.

Displaying Strings in UI Text

You can use Unity’s Text component to display strings on the screen.

using UnityEngine;
using UnityEngine.UI;

public class ScoreDisplay : MonoBehaviour
{
    public Text scoreText;
    private int score = 0;

    void Start()
    {
        UpdateScore();
    }

    public void UpdateScore()
    {
        scoreText.text = $"Current Score: {score}"; // Using string interpolation
    }
}

Printing Log Messages

You can use the Debug.Log method to print strings to the console.

Debug.Log("The game has started!"); // Output to the console

Creating a Dialogue System

You can implement a simple dialogue system using strings. Each part of the dialogue is stored as a string and displayed based on specific conditions.

public class Dialogue : MonoBehaviour
{
    private string[] dialogues = {
        "Hello! I am Character A.",
        "How can I assist you here?",
        "Have a great day!"
    };

    private int currentDialogueIndex = 0;

    public void ShowNextDialogue()
    {
        if (currentDialogueIndex < dialogues.Length)
        {
            Debug.Log(dialogues[currentDialogueIndex]);
            currentDialogueIndex++;
        }
    }
}

Practical Uses of String Formatting

String formatting is very useful for displaying various data in games. When dealing with scores, levels, item counts, etc., formatting can present this information more intuitively and clearly.

Scoreboard Example

Let’s examine an example of formatting and displaying a player’s score on a scoreboard.

using UnityEngine;
using UnityEngine.UI;

public class ScoreBoard : MonoBehaviour
{
    public Text scoreText;
    private int playerScore;

    public void AddScore(int points)
    {
        playerScore += points;
        UpdateScoreDisplay();
    }

    private void UpdateScoreDisplay()
    {
        scoreText.text = $"Player Score: {playerScore:N0}"; // Using thousand separators
    }
}

Useful Tips for Handling Strings

Here are a few useful tips when working with strings.

String Comparison

When comparing strings, you can use the String.Equals method or the == operator. If you want to ignore case during comparison, use String.Compare.

bool isSame = String.Equals("apple", "Apple", StringComparison.OrdinalIgnoreCase); // true

Creating Infinite Strings

If you want to repeat a string infinitely, you can use the String.Concat method. However, be cautious as this may increase memory usage, so use appropriately.

string repeated = String.Concat(Enumerable.Repeat("A", 1000)); // A string of 'A' repeated 1000 times

Conclusion

So far, we have covered the basic concepts of strings in C# and how to utilize them in Unity. Strings are essential elements in Unity development, used in various areas such as dialogue systems, scoreboards, and UI. I hope the contents discussed in this tutorial help you develop better games.

Unity Basics Course: Loops – while

Table of Contents

  1. 1. Introduction
  2. 2. while Syntax
  3. 3. How to Use a while Loop
  4. 4. Examples
  5. 5. Common Mistakes
  6. 6. Best Practices
  7. 7. Conclusion

1. Introduction

Loops are a very important concept in programming, allowing you to repeatedly execute code while a certain condition is true. In Unity, loops are frequently used to repeatedly execute game logic, and among them, the while loop is a simple and powerful tool that runs until a specific condition is met. This article will cover the basic concepts, syntax, usage, examples, mistakes, and best practices of the while loop in detail.

2. while Syntax

while loop’s basic structure is as follows:

while (condition) {
    // Code to execute
}

The code inside the loop runs only if the condition evaluates to true, and the loop terminates when the condition evaluates to false.

3. How to Use a while Loop

while loops are primarily used in the following scenarios:

  • When you need to repeat until a state changes
  • When continually receiving user input
  • When creating an infinite loop (exercise caution!)

When using loops, care must be taken to ensure that the condition will eventually evaluate to false so that the loop can terminate.

4. Examples

Below is an example of using a while loop in Unity.

Example 1: Counting

Let’s look at a simple counting example. The code below prints numbers from 1 to 10.

using UnityEngine;

public class CountExample : MonoBehaviour {
    void Start() {
        int count = 1;
        while (count <= 10) {
            Debug.Log(count);
            count++;
        }
    }
}

Example 2: Infinite Loop

An example of an infinite loop that requires caution. The code below creates a loop that never terminates.

using UnityEngine;

public class InfiniteLoop : MonoBehaviour {
    void Start() {
        while (true) {
            Debug.Log("This message will be printed endlessly.");
        }
    }
}

5. Common Mistakes

Common mistakes when using loops include:

  • Incorrectly setting the termination condition, leading to infinite loops
  • Not updating the condition variable, causing the loop to run indefinitely
  • Improperly manipulating variables without side effects

6. Best Practices

Here are some best practices to consider when using a while loop:

  • Set a clear termination condition.
  • If operations occur inside the loop, change the state appropriately.
  • Consider limiting the number of iterations for easier debugging.

7. Conclusion

Loops are a very important tool in all programming languages, including Unity. In particular, the while loop allows you to repeatedly execute code until a specific condition is satisfied. To use it effectively, one should be cautious in setting conditions, avoid common mistakes, and follow best practices. I hope this article deepens your understanding of the while loop.