Unity Basics Course: Access Modifiers

As we begin developing with Unity, we will write code and create objects. In this process, we need to understand one of the core concepts of Object-Oriented Programming (OOP): ‘access modifiers’. Access modifiers control the access rights to the members (variables, methods) of a class or object, making data protection and code maintenance easier.

1. What are Access Modifiers?

Access modifiers are keywords that allow setting the level of access to the members of a class in object-oriented languages. Through them, we can control which members can be accessed, thereby enhancing code safety and reducing unnecessary errors.

2. Access Modifiers Used in Unity

The main access modifiers used in Unity are as follows:

  • public: Accessible from any class
  • private: Accessible only within the class
  • protected: Accessible in the class and in derived classes
  • internal: Accessible only within the same assembly
  • protected internal: Accessible within classes in the same assembly and in derived classes

2.1 public

When using the public access modifier, the member can be accessed from any class. This allows for easy reference from other objects.

public class Player
{
    public int health;
    public void TakeDamage(int damage)
    {
        health -= damage;
    }
}

2.2 private

The private access modifier is used to protect data. The member can only be accessed within the declared class.

public class Player
{
    private int health;
    public void TakeDamage(int damage)
    {
        health -= damage;
    }
}

2.3 protected

The protected access modifier allows access only within the class and in classes that inherit from it.

public class Player
{
    protected int health;
}

public class Warrior : Player
{
    public void Heal()
    {
        health += 10;
    }
}

2.4 internal

The internal access modifier refers to members that can only be accessed within the same assembly.

2.5 protected internal

Protected internal is an access modifier that combines the characteristics of protected and internal. That is, it is accessible within the same assembly and also in derived classes.

3. Reasons for Using Access Modifiers

There are several reasons for using access modifiers.

  • Data Protection: Prevents direct access to data from outside, avoiding errors that could occur due to incorrect values.
  • Code Maintenance: Access modifiers help clarify the structure of the code, making it easier to maintain.
  • Encapsulation: Encapsulates the internal implementation of a class, preventing unintended access from outside.

4. Conclusion

In object-oriented languages like Unity, access modifiers are essential for enhancing the stability of code and providing clarity of structure. Understanding the basic concepts and using them effectively is a significant aid in becoming proficient as a developer. Continue to deepen your learning about access modifiers with various examples.

Basic Unity Course: Shooting 2 – Shooting Without Bullets

Hello! In this tutorial, we will learn how to implement the interesting concept of “shooting without bullets” in Unity. The concept of shooting without bullets can act as an element that provides a more creative and new gameplay experience, going beyond the traditional shooting game’s bullet firing mechanism.

In this tutorial, we will cover how players interact with enemies without using bullets, how enemies recognize the player’s position, and how players attack. We will also explain the necessary C# scripts and setup methods to implement these elements in detail.

1. Basic Concept of Shooting Without Bullets

Shooting without bullets is a way for players to hit enemies within a certain range. This can be implemented in the form of melee attacks or area attacks that can inflict damage on enemies every time the player presses the attack button. This method can create various gameplay mechanics instead of simple bullet firing.

For example, consider a system where the player uses an attack like a laser that hits all enemies in the direction it points. This requires players to strategize their attacks, while enemies may take actions to evade. This mechanism offers a unique gaming experience.

2. Setting Up the Unity Project

The first step is to set up a Unity project. Launch Unity and create a new 3D project. After setting the project name and save location, create the project.

2.1 Configuring the Scene

The scene needs a player character, enemies, and a UI to display the attack range. Follow the steps below to configure the scene:

  • Creating the Player Character: Create a 3D model or replace it with Unity’s basic cube object to create the player character.
  • Placing Enemies: Place several enemy models in the scene to interact with the player from various positions.
  • Adding UI Elements: Add a UI Canvas to visually represent the attack range and create a UI object to indicate the attack radius.

3. Writing the Player Script

Now, we will write a player script to allow the player to hit enemies when attacking. Create a C# script and name it ‘PlayerController’.

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float attackRange = 5f;       // Attack range
    public LayerMask enemyLayer;        // Enemy layer

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) // Attack with the space key
        {
            Attack();
        }
    }

    void Attack()
    {
        Collider[] hitEnemies = Physics.OverlapSphere(transform.position, attackRange, enemyLayer);
        foreach (Collider enemy in hitEnemies)
        {
            // Add logic to hit the enemy here
            Debug.Log("Hit " + enemy.name);
        }
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, attackRange); // Visualize attack range
    }
}

The above code allows the player to detect enemies within the specified attack range when the space bar is pressed. It uses the Physics.OverlapSphere function to detect enemies around the player and logs a message every time an enemy is detected.

4. Writing the Enemy Script

Now, let’s write a script that defines the behavior of the enemy when receiving damage from the player’s attack. Create a new script named ‘EnemyController’.

using UnityEngine;

public class EnemyController : MonoBehaviour
{
    public int health = 100; // Enemy health

    public void TakeDamage(int damage)
    {
        health -= damage;
        if (health <= 0)
        {
            Die();
        }
    }

    void Die()
    {
        Debug.Log(name + " has died!");
        Destroy(gameObject); // Remove enemy object
    }
}

In the above code, the enemy has health and takes damage from the player, reducing their health. If health falls to 0 or below, the enemy dies, and the game object is destroyed.

Now let’s add the logic for the enemy taking damage to the Attack() method in the PlayerController.

void Attack()
{
    Collider[] hitEnemies = Physics.OverlapSphere(transform.position, attackRange, enemyLayer);
    foreach (Collider enemy in hitEnemies)
    {
        EnemyController enemyController = enemy.GetComponent<EnemyController>();
        if (enemyController != null)
        {
            enemyController.TakeDamage(10); // Specify damage amount
            Debug.Log("Hit " + enemy.name);
        }
    }
}

5. Testing

After writing all the scripts, press the play button in the Unity editor to test. Check if the nearby enemies take damage when you press the space bar. When an enemy dies, a related message will be output in the log.

During this process, you can adjust the attack range and modify the enemy’s health for various gameplay adjustments.

6. Additional Expansion Ideas

In this tutorial, we implemented a simple form of shooting without bullets. Here are some ideas for expanding this:

  • Adding Different Types of Attacks: Enhance the variety of the game by adding various attack methods that players can use.
  • Changing Enemy Behavior Patterns: Add behaviors where enemies not only chase the player but also evade or counterattack.
  • Items and Power-ups: Implement mechanisms that increase attack power or range by adding items or power-ups that players can use.

7. Conclusion

The shooting without bullets game mechanism provides players with a new experience and enhances the game’s strategy. Having learned the basic implementation methods in this tutorial, it is up to you to advance this system with more features and elements.

The process of creating games with Unity is challenging but simultaneously a creative and enjoyable journey. I hope this will be of great help on your path ahead. Thank you!

Unity Basics Course: C# Character (char)

In this course, we will explain in detail about the basic character data type char used in C# programming within Unity. A character (char) is a basic element that makes up a string (string), representing a single character and can be utilized in various ways.

1. What is a character (char)?

char is a data type in C# for storing a single character. The char type in C# can store Unicode characters, and each character occupies 2 bytes of memory space. Unicode is an internationally used character set that includes characters from various languages such as Korean, English, and Japanese.

1.1. Characteristics of char

  • Single character storage: char can only store one character.
  • Unicode support: Supports all Unicode characters, allowing for the use of various character sets.
  • Constant type: char is defined by enclosing it in single quotes (' ').

1.2. Declaring and initializing char

Here is how to declare and initialize a char variable in C#.

char letter = 'A';

In the example above, the letter variable stores the character ‘A’.

2. Example of using char

Now let’s look at some examples of using char.

2.1. Printing a character

Let’s write a simple example that prints the value of char to the console.

using UnityEngine;

public class CharExample : MonoBehaviour
{
    void Start()
    {
        char letter = 'B';
        Debug.Log("Stored character: " + letter);
    }
}

The above code declares a char variable in Unity and outputs it to the log.

2.2. Utilizing ASCII values

The char type in C# can perform basic calculations related to the ASCII character set. Each character has a special ASCII value, which can be obtained using a char variable.

char letter = 'C';
int asciiValue = letter; // ASCII value

Debug.Log("Character: " + letter + ", ASCII value: " + asciiValue);

The above example includes printing the ASCII value of the character ‘C’.

2.3. Combining multiple char values

When combining multiple char values, they need to be converted to a string. Converting to string allows the use of various functionalities.

char firstLetter = 'H';
char secondLetter = 'i';
string greeting = "" + firstLetter + secondLetter; // "Hi"

Debug.Log("Greeting: " + greeting);

This example combines the two characters ‘H’ and ‘i’ to create the string “Hi” and then outputs it.

3. Difference between char and string

A character and a string are different data types, and there is a difference in how they are used. char stores one character, while string works like an array that can store multiple characters.

3.1. Declaring and initializing string

string name = "Unity";

In the example above, name stores the string “Unity”.

3.2. Converting character to string

To convert a char to a string, you can use the ToString() method.

char letter = 'D';
string letterString = letter.ToString(); // "D"

3.3. Accessing characters in a string

You can access each character in a string via indices.

string word = "Hello";
char firstChar = word[0]; // 'H'

4. Utilizing char in Unity

There are several ways to utilize char in Unity projects. It can be used in various areas such as displaying character states, changing UI text, and handling key inputs.

4.1. Handling key inputs

Unity provides functionality to handle user key inputs. Here is an example of detecting key inputs and setting a char type variable based on the pressed key.

void Update()
{
    if (Input.GetKeyDown(KeyCode.A))
    {
        char keyPressed = 'A';
        Debug.Log("Pressed key: " + keyPressed);
    }
}

4.2. Adding character to string

To add a character to a string, you can use the += operator.

string message = "Hello";
message += '!';
Debug.Log(message); // "Hello!"

5. char and conditional statements

You can use conditional statements to perform specific actions based on the char value. The following example outputs different messages based on the character input by the user.

char userInput = 'Y';

if (userInput == 'Y' || userInput == 'y')
{
    Debug.Log("The user entered 'Y' or 'y'.");
}
else
{
    Debug.Log("Another character was entered.");
}

6. Conclusion

In this course, we learned in detail how to utilize the char type in C# within Unity. Understanding and using character data is a fundamental element in game development, which will be very helpful in future development processes.

Additionally, if you learn more about various methods or properties related to char, it will greatly help deepen your programming knowledge. I encourage you to utilize the char type in your future projects.

Thank you!

Unity Basics Course: C# Integer (int)

This course will cover the integer (int) data type in C# used in the Unity development environment. Integers are one of the most fundamental and essential data types in programming. We will explore how to easily understand and utilize integers in game development.

1. Definition of Integer (int)

In C#, int represents a 32-bit signed integer. This means that int can represent values from -2,147,483,648 to 2,147,483,647. Integers are primarily used for numerical calculations or in loops, and they are widely utilized in game development in various contexts such as player scores, levels, and lives.

2. Declaration and Initialization of Integer (int)

To declare and initialize an int variable in C#, you can do the following:

int score = 0;

The above code declares an integer variable named score and initializes its value to 0. You can now use this variable to perform various calculations.

3. Basic Operations on Integers

C# allows you to perform basic arithmetic operations on integers. The main operators are as follows:

  • + : Addition
  • - : Subtraction
  • * : Multiplication
  • / : Division
  • % : Modulus

Example: Integer Operations


int a = 10;
int b = 3;

int sum = a + b;     // Addition
int difference = a - b; // Subtraction
int product = a * b; // Multiplication
int quotient = a / b; // Division
int remainder = a % b; // Modulus

The above code performs each arithmetic operation on two integers a and b. As a result, sum will store 13, difference will store 7, product will store 30, quotient will store 3, and remainder will store 1.

4. Increment and Decrement Operators for Integers

C# allows the use of increment and decrement operators on integers. These operators are useful for increasing or decreasing the value of a variable by 1.

  • ++ : Increments by 1
  • -- : Decrements by 1

Example: Increment and Decrement Operators


int counter = 0;
counter++; // counter is now 1.
counter--; // counter is now 0.

5. Conversion of Integers

In game development, it may be necessary to perform conversion operations between different data types. In C#, you can use the Convert class to convert data in various ways. Here’s how to convert integers to other data types:


int number = 42;
float floatNumber = Convert.ToSingle(number); // Convert int to float
string strNumber = number.ToString(); // Convert int to string

6. Conditionals Using Integers

Integers are widely used in conditionals as well. In particular, you can evaluate conditions using variables in if statements and loops.


int health = 100;

if (health <= 0) {
    Debug.Log("The player has died.");
} else {
    Debug.Log("The player is alive.");
}

7. Utilization of Integer (int) in Unity

In game development, integers are employed in many different ways. Here are a few examples:

  • Score System: Store player scores and update them whenever the score increases or decreases.
  • Level Management: Manage the character's level in the game as an integer variable, increasing the level according to experience points.
  • Time Calculation: Set triggered events in the game using an integer timer.

Example: Implementing Score System


using UnityEngine;

public class ScoreManager : MonoBehaviour {
    private int score;

    void Start() {
        score = 0; // Initialize score at the start of the game
    }

    public void AddScore(int points) {
        score += points; // Add score
        Debug.Log("Current Score: " + score);
    }
}

8. Common Errors and Precautions

There are several things to avoid when using integers in C#. For example:

  • Overflow: The int type cannot exceed its maximum value. If it does, an overflow occurs, leading to incorrect results. Caution is required.
  • Type Conversion Errors: When converting fractional values to integers, the decimal part is discarded, leading to data loss. This should be kept in mind.

9. Conclusion

In this course, we have explored the integer (int) data type in C# within Unity in depth. Integers are a fundamental element of game development and can be utilized effectively. Understanding the characteristics, operations, conversions, and applications of integers in Unity will greatly aid in successful game development. Practice with more examples and applications to use C# integers more proficiently.

10. Reference Materials

If you want to learn more about C# and Unity programming, please refer to the following resources:

Basic Unity Course: Bullet Firing

In this tutorial, we will implement a simple bullet shooting system using Unity. This tutorial is based on a basic understanding of Unity and will be conducted step by step so that beginners can easily follow along. By completing this tutorial, you will lay the foundation to apply the shooting functionality in 2D or 3D games.

Table of Contents

1. Setting Up

To effectively use Unity, appropriate setup is necessary. Download and install the latest version of Unity from the Unity Hub. Use the package manager to install the packages needed for the current project. In particular, the Physics and 2D Physics packages are required.

2. Creating a Unity Project

Open Unity Hub and create a new project. Choose between 2D or 3D as you prefer. It is recommended to proceed in 3D for this tutorial. Set the project name to ‘BulletShooter’, specify the path, and then click the ‘Create’ button.

3. Adding and Setting Up Sprites

You need to add the sprites for the bullet and the gun. Prepare the sprite images and drag them into the ‘Assets’ folder to add them. Then, adjust the appearance and size of the images using the Inspector panel and Sprite Renderer for each sprite.

3.1. Creating Bullet Sprite

After selecting the bullet sprite, click the Add Component button to add Rigidbody and Collider. By disabling the gravity of the Rigidbody, the bullet will be shot in a straight line.

3.2. Creating Gun Sprite

Similarly, add Rigidbody and Collider to the gun’s sprite. Position the gun appropriately to adjust the firing direction of the bullet.

4. Creating the Bullet Script

Now let’s write a script to define how the bullet is fired. Right-click in the empty space of the ‘Assets’ folder, select Create > C# Script, and create a script named ‘Bullet’.

4.1. Writing Bullet.cs Code

    
    using UnityEngine;
    
    public class Bullet : MonoBehaviour
    {
        public float speed = 20f;

        void Start()
        {
            Rigidbody rb = GetComponent();
            rb.velocity = transform.forward * speed;
        }

        void OnTriggerEnter(Collider other)
        {
            if (other.CompareTag("Enemy"))
            {
                Destroy(other.gameObject);
                Destroy(gameObject);
            }
        }
    }
    

The above code allows the bullet to move forward at the speed set through the Rigidbody component upon firing. It is implemented to destroy the bullet and the enemy object upon collision.

5. Creating the Gun Control Script

Now it’s time to add the functionality for the gun to shoot bullets. Create a new script called ‘Gun’ and write the following code.

5.1. Writing Gun.cs Code

    
    using UnityEngine;

    public class Gun : MonoBehaviour
    {
        public GameObject bulletPrefab;
        public Transform firePoint;
        public float fireRate = 1f;
        private float nextFireTime = 0f;

        void Update()
        {
            if (Input.GetButton("Fire1") && Time.time >= nextFireTime)
            {
                nextFireTime = Time.time + 1f / fireRate;
                Shoot();
            }
        }

        void Shoot()
        {
            Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        }
    }
    

This script shoots a bullet when the user presses the mouse button. It creates an instance at the firePoint location to enable the bullet’s shooting mechanism.

6. Testing and Debugging

Now that everything is set up, you need to test whether the code works without issues. Click the play button in the Unity Editor to run the game. Press the mouse button to check if the bullets are being fired. Also, confirm that bullets are destroyed upon contact with enemies.

7. Conclusion

In this tutorial, we built a simple bullet shooting system using Unity. We covered sprite setup, using Rigidbody, and implementing the shooting functionality through scripts. Now you can use this foundational knowledge to advance into more complex and interesting game development. Unity has many features, so keep practicing and improving.