Unity Basics Course: What is a Variable?

Hello! In this course, we will dive deep into variables used in Unity. A variable is one of the basic concepts in programming, serving as a space to store and manipulate data we desire. Variables play a very important role in the process of developing games in Unity.

1. Definition of Variables

A variable refers to a memory space that stores data. Each variable has a specific name, through which we can reference or modify the data stored in the variable. For example, we use variables to store information like the player’s score, position, and lives in the game.

2. Types of Variables

There are several types of variables used in Unity, each differing based on the type of data they can store.

2.1 Integer (Int)

Integer variables are used to store whole number values. They are commonly used in most games to store scores, levels, lives, etc.

int playerScore = 0; // Initialize player's score

2.2 Float

Float variables are used to store values that include decimal points. They are often used in games to store time, speed, rewards, and more.

float playerSpeed = 5.5f; // Set player's speed

2.3 Boolean

Boolean variables can have one of two states: true or false. They are primarily used to check the state or conditions in the game.

bool isGameOver = false; // Initialize game over state

2.4 String

String variables store data made up of a collection of characters. They are suitable for storing user names, messages, etc.

string playerName = "Player1"; // Set player's name

3. Declaration and Initialization of Variables

To use a variable, you must first declare it and initialize it as needed. Declaring a variable involves specifying its type and name. Initialization is the step where a value is assigned after the variable is declared.

3.1 Variable Declaration

int playerHealth; // Variable declaration

3.2 Variable Initialization

playerHealth = 100; // Variable initialization

You can also perform variable declaration and initialization simultaneously:

int playerHealth = 100; // Declare and initialize at the same time

4. Using Variables

Now that we have declared and initialized our variables, let’s look at how to use them in game logic. Here are some common examples of using variables.

4.1 Outputting Variables

To output a variable, use the Debug.Log() method.

Debug.Log(playerScore); // Output player's score

4.2 Variable Operations

Various operations can be performed on variables. For instance, to increase the score, we can do the following:

playerScore += 10; // Increase score by 10

5. Scope of Variables

The scope of a variable refers to the range of code blocks within which the variable can be used. In Unity, variables can be declared in various scopes.

5.1 Global Variable

A global variable is a variable that can be accessed from all methods within a class. It is mostly declared as a field of the class.

public int playerScore; // Declared as a global variable

5.2 Local Variable

A local variable is a variable declared within a method, and it can only be used within that method’s scope.

void Start() {
    int playerHealth = 100; // Declared as a local variable
}

6. Importance of Variables

Variables are essential in game development, as they are necessary for storing and manipulating data. Understanding variables significantly aids in learning broader concepts like object-oriented programming, algorithms, and data structures.

7. Conclusion

In this course, we explored variables in Unity. By effectively utilizing variables, you can create more complex and interesting games. In the next session, we will look into conditional statements and loops. If you have questions or curiosities, please leave a comment!

Note: The types and usage of variables are fundamental concepts not only in Unity but in all programming languages. Therefore, it is beneficial to study various languages to learn how to handle variables.
Example Code: Below is an example of a simple Unity script. This script implements the logic to increase the player’s score.

using UnityEngine;

public class Player : MonoBehaviour {
    public int playerScore = 0;

    void Start() {
        Debug.Log("Game Start! Score: " + playerScore);
    }

    void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
            playerScore += 10;
            Debug.Log("Score Increased! Current Score: " + playerScore);
        }
    }
}

Unity Basics Course: Loops – for

When developing games in Unity, handling repetitive tasks is very important.
To achieve this, programming uses the concept of ‘loops’, with the ‘for’ loop being one of the most common and powerful tools.
In this article, we will specifically explore how to utilize the ‘for’ loop in Unity.

1. The Necessity of Loops

In game development, various elements are used repetitively.
For example, when spawning multiple enemy characters or changing the properties of game objects in bulk, loops are extremely useful.
Performing these tasks manually without loops would lead to inefficient and complex code, making maintenance difficult.

2. Overview of the for Loop

The ‘for’ loop is a structure that repeatedly executes code while a specific condition is met.
The basic syntax is as follows:

        for (initialization; condition; increment) {
            // Code to repeat
        }
    

3. Components of the for Loop

Initialization: Initializes variables before the loop starts.
Condition: The loop repeats as long as this condition is true.
Increment: Increases or decreases the variable with each iteration.

4. Example of the for Loop

Below is a simple example of using the ‘for’ loop in Unity.
This example contains code that creates 10 enemy characters.

        using UnityEngine;

        public class EnemySpawner : MonoBehaviour {
            public GameObject enemyPrefab;

            void Start() {
                for (int i = 0; i < 10; i++) {
                    Instantiate(enemyPrefab, new Vector3(i * 2.0F, 0, 0), Quaternion.identity);
                }
            }
        }
    

This code uses a prefab called ‘enemyPrefab’ to create 10 enemies.
Each enemy is placed at intervals of 2.0 units along the x-axis.

5. Nested for Loops

The ‘for’ loop can be nested, making it useful for handling two-dimensional arrays or grid-based elements.
For example, here is a code example for creating a 5×5 grid.

        using UnityEngine;

        public class GridSpawner : MonoBehaviour {
            public GameObject tilePrefab;

            void Start() {
                for (int x = 0; x < 5; x++) {
                    for (int z = 0; z < 5; z++) {
                        Instantiate(tilePrefab, new Vector3(x, 0, z), Quaternion.identity);
                    }
                }
            }
        }
    

The above code uses two ‘for’ loops to create a grid of 5×5 size.
Each tile is created using the ’tilePrefab’.

6. for Loops and Arrays

The ‘for’ loop is very effective when using arrays.
Let’s look at a simple example that accesses every element in an array.

        using UnityEngine;

        public class ArrayExample : MonoBehaviour {
            int[] numbers = { 1, 2, 3, 4, 5 };

            void Start() {
                for (int i = 0; i < numbers.Length; i++) {
                    Debug.Log("Number: " + numbers[i]);
                }
            }
        }
    

This code outputs every element of the ‘numbers’ array.
It dynamically obtains the size of the array using ‘numbers.Length’, so if the array size changes, the code can still be used without modification.

7. Cautions When Using for Loops

When using the ‘for’ loop, be careful not to fall into an infinite loop.
If the condition is set to always be true, the program will continue to run indefinitely.
Always set clear termination conditions and design the loop to allow for interruptions using the ‘break’ statement if necessary.

8. Conclusion

In this lecture, we explored how to use the ‘for’ loop in Unity.
Loops are a very important concept in programming, and effectively utilizing them can greatly enhance code readability and maintainability.
Familiarize yourself with the use of loops through various examples, and apply them to your own game development projects.

3.1 Unity C#, Programming, Coding, Algorithm

Unity is a powerful engine for game development, enabling the creation of various games and simulations using the C# programming language.
This course will cover in detail how to program in Unity using C# and various techniques for applying algorithms.

1. Introduction to Unity and C#

Unity is an integrated development environment (IDE) that helps users easily create interactive 2D and 3D content.
Here, C# is used as the main scripting language, allowing complex logic to be implemented through interactions with game objects.
By leveraging the object-oriented programming (OOP) characteristics of C#, users can manipulate the various features and elements of Unity.

1.1 Basic Syntax of C#

The basic syntax of C# is highly readable, supports strong type checking, and offers various features.
For example, you will learn about variable declarations, data types, conditional statements, loops, and functions.
A simple example of variable declaration is as follows:

int score = 0;
string playerName = "Player";

2. Programming in Unity

Programming in Unity is primarily done by writing script files.
Typically, scripts are created by inheriting from the MonoBehaviour class and added to game objects.

2.1 Key Methods of MonoBehaviour

MonoBehaviour is the most important class for using scripts in Unity,
providing several event methods. Some of these include:

  • Awake(): Called when the script is initialized.
  • Start(): Called once before the first frame.
  • Update(): Called every frame.

2.2 Game Objects and Components

Everything in Unity consists of game objects, and each object can have multiple components.
Components define the properties and behaviors of objects. For example, adding a Rigidbody component allows the object to be affected by the physics engine.

3. Algorithms and Data Structures

Algorithms and data structures are very important when designing game logic in Unity.
Using appropriate algorithms can maximize performance and improve code efficiency.

3.1 Basic Data Structures

Commonly used basic data structures in Unity include arrays, lists, and dictionaries.
These structures can be used to manage data effectively.
For example, let’s look at how to manage enemy NPCs using a list:

List<Enemy> enemies = new List<Enemy>();

3.2 Efficiency of Algorithms

When selecting algorithms, it is essential to consider time complexity and space complexity.
For instance, common examples of sorting algorithms include bubble sort, selection sort, and quick sort.
Understanding the pros and cons of each algorithm and choosing the one that fits a specific situation is crucial.

4. Conclusion

In this course, we learned the basics of programming in Unity using C# and the importance of algorithms.
Unity and C# are powerful tools in game development, and the process of creating new games with them is very exciting and full of learning opportunities.
I hope to become a more advanced developer through deeper learning in the future.

5. References

Unity Basic Course: Vertical Rotation of the View

Unity is a powerful engine for game development that provides the ability to create a variety of 2D and 3D applications.
In this course, we will cover how to rotate the camera’s view up and down in Unity.
Through this process, you will learn how to manipulate the player’s viewpoint and, further, provide an immersive experience within the game.

1. Basic Setup

First, launch Unity and create a new project.
Select the 3D project and set an appropriate project name. After the project is launched, configure the basic scene.
In the scene view, select the Main Camera object and adjust the camera’s position and rotation angles.
The camera serves as the reference to display all game objects, so it must be properly set.

2. Setting Up the Camera and Player Character

To set up the player character, select 3D Object > Cylinder from the GameObject menu to create a basic character model.
This object will become a simple form of the player character. Rename the created cylinder to ‘Player’, and
set the Main Camera as the child of the player.
This will allow the camera to move with the player.

3. Setting Up the Input System

To implement the up and down rotation of the camera, we will write a script for input processing. Create a folder named Scripts inside the Assets folder, and
create a script named CameraController.cs within it.
Paste the following code into the script:


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour
{
    public Transform player; // Player character
    public float sensitivity = 5.0f; // Mouse sensitivity
    public float clampAngle = 80.0f; // Rotation limit angle

    private float rotX = 0.0f; // Up and down rotation angle
    private float rotY = 0.0f; // Left and right rotation angle

    void Start()
    {
        rotX = transform.localEulerAngles.x; // Set initial up and down rotation angle
        rotY = transform.localEulerAngles.y; // Set initial left and right rotation angle

        Cursor.lockState = CursorLockMode.Locked; // Hide the mouse cursor
    }

    void Update()
    {
        rotX -= Input.GetAxis("Mouse Y") * sensitivity; // Calculate up and down rotation with mouse Y input
        rotY += Input.GetAxis("Mouse X") * sensitivity; // Calculate left and right rotation with mouse X input

        rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle); // Limit the rotation angle

        transform.localEulerAngles = new Vector3(rotX, rotY, 0); // Apply rotation
        player.Rotate(0, Input.GetAxis("Mouse X") * sensitivity, 0); // Apply left and right rotation to the player character
    }
}

After writing the script, select the Main Camera object, click the Add Component button, and add the CameraController script you created.
Then drag the Player object to the Player property of the CameraController script to link it.

4. Testing and Adjusting

Now that all settings are complete, save the scene and click the play button to test the game.
You can see the camera rotating up and down as you move the mouse, and the player character rotating left and right.
If you want to adjust the sensitivity, you can change the value of the sensitivity variable to achieve your desired sensitivity.

5. Implementing Additional Features

In addition to basic up and down rotation, you can add more diverse features to provide a better user experience.
For example, you can use the SmoothDamp function to smooth the camera’s movement.


private Vector3 velocity = Vector3.zero; // Velocity variable

void LateUpdate()
{
    Vector3 targetPosition = player.position; // Target position
    transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, 0.3f); // Smooth camera movement
}

This shows how to smoothly move the camera considering the speed between frames using the LateUpdate method.
This allows the camera to follow the player more naturally.

6. Conclusion

Through this lecture, we learned the basic method for rotating the camera’s view up and down in Unity and how to manipulate the player’s viewpoint.
Based on this foundation, you can utilize it for various game design and implementation.
Additionally, Unity offers many more features, so continuously learning and advancing is important.

In the future, we will cover various topics in the Unity beginner’s course series, so please stay tuned!
Happy Coding!

Basic Unity Course: Save and Load Functionality, Data Loading

Storing and retrieving user data in game development is a very important aspect.
In this tutorial, we will learn in detail about how to save and load data in Unity.
There are difficult parts, but if you follow step by step, you will surely succeed, so don’t worry!

Table of Contents

  1. 1. The Necessity of Data Storage
  2. 2. How to Save Data in Unity
  3. 3. Saving and Loading Data with JSON
  4. 4. Simple Saving and Loading with PlayerPrefs
  5. 5. Complex Data Storage Using XML or BinaryFormatter
  6. 6. Practice: Implementing Data Saving and Loading
  7. 7. Conclusion

1. The Necessity of Data Storage

It is essential to store the player’s progress or settings while playing the game.
If data is not saved, players would have to start over every time they begin the game,
which degrades the gaming experience. For example, by saving information such as level completion, scores, and item possession,
players can maintain their progress. Here, data storage can be primarily divided into two main purposes:

  • Saving the player’s game progress
  • Saving game settings and options

2. How to Save Data in Unity

In Unity, data can be saved in various ways. We mainly use the following methods:

  • PlayerPrefs: A way to save data with simple key-value pairs.
  • JSON File: A useful method for saving structured data.
  • XML File: A method for clearly defining and saving the structure of data.
  • BinaryFormatter: A method to save and load objects through serialization.

3. Saving and Loading Data with JSON

JSON is a widely used format for structurally storing data. By learning how to use JSON in Unity,
you can easily save and load complex data structures. Here’s how to implement saving and loading data using JSON.

3.1 JSON Data Class

You first need to create a class that defines the data to be saved. For example, you can create a class to store player information like this:


    [System.Serializable]
    public class PlayerData {
        public string playerName;
        public int playerScore;
        public float[] playerPosition;

        public PlayerData(string name, int score, Vector3 position) {
            playerName = name;
            playerScore = score;
            playerPosition = new float[] { position.x, position.y, position.z };
        }
    }
    

3.2 Saving JSON Data

You can convert the data you defined above into JSON format and save it to a file.
Here is an example of saving JSON data:


    public void SaveData(PlayerData data) {
        string json = JsonUtility.ToJson(data);
        System.IO.File.WriteAllText(Application.persistentDataPath + "/playerdata.json", json);
    }
    

3.3 Loading JSON Data

The method for loading the saved JSON data is as follows:


    public PlayerData LoadData() {
        string path = Application.persistentDataPath + "/playerdata.json";
        if (System.IO.File.Exists(path)) {
            string json = System.IO.File.ReadAllText(path);
            return JsonUtility.FromJson<PlayerData>(json);
        }
        return null;
    }
    

4. Simple Saving and Loading with PlayerPrefs

PlayerPrefs is the easiest way to save simple data.
It is primarily used for saving strings, integers, and floating-point data.
It is very straightforward to use, and you can save and load data in the following way.

4.1 Saving Data to PlayerPrefs


    public void SaveScore(int score) {
        PlayerPrefs.SetInt("PlayerScore", score);
        PlayerPrefs.Save();
    }
    

4.2 Loading Data from PlayerPrefs


    public int LoadScore() {
        return PlayerPrefs.GetInt("PlayerScore", 0); // Default value is 0
    }
    

5. Complex Data Storage Using XML or BinaryFormatter

For complex data structures, data can be stored using XML or BinaryFormatter.
Both methods can save data in object form, with BinaryFormatter being more concise and performant, but
XML is human-readable, making it advantageous for data verification.

5.1 Saving XML Data


    using System.Xml.Serialization;

    public void SaveToXml(PlayerData data) {
        XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
        using (FileStream stream = new FileStream(Application.persistentDataPath + "/playerdata.xml", FileMode.Create)) {
            serializer.Serialize(stream, data);
        }
    }
    

5.2 Loading XML Data


    public PlayerData LoadFromXml() {
        XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
        using (FileStream stream = new FileStream(Application.persistentDataPath + "/playerdata.xml", FileMode.Open)) {
            return (PlayerData)serializer.Deserialize(stream);
        }
    }
    

5.3 Saving BinaryFormatter Data


    using System.Runtime.Serialization.Formatters.Binary;

    public void SaveToBinary(PlayerData data) {
        BinaryFormatter formatter = new BinaryFormatter();
        using (FileStream stream = new FileStream(Application.persistentDataPath + "/playerdata.dat", FileMode.Create)) {
            formatter.Serialize(stream, data);
        }
    }
    

5.4 Loading BinaryFormatter Data


    public PlayerData LoadFromBinary() {
        BinaryFormatter formatter = new BinaryFormatter();
        using (FileStream stream = new FileStream(Application.persistentDataPath + "/playerdata.dat", FileMode.Open)) {
            return (PlayerData)formatter.Deserialize(stream);
        }
    }
    

6. Practice: Implementing Data Saving and Loading

Let’s proceed with a simple practice based on what we have learned so far.
We will implement a feature that allows us to input the player’s name and score, save them, and later load them.

6.1 Creating the UI

Set up a UI in the Unity Editor to receive input.
Place InputField and Button, and configure it to receive player names and scores.

6.2 Writing the Script

Now, write a script to handle user input and implement the saving and loading functionality.
Test the implemented features to ensure they work correctly.

7. Conclusion

Today we learned about various methods of saving and loading data in Unity.
We learned to save simple data using PlayerPrefs, and how to handle complex data using JSON or XML.
I hope these features will be very helpful in your game development.
Always practice and find your own way to save data!

Thank you for reading! Happy gaming!