unity basic course: hide mouse cursor

In this tutorial, we will learn how to hide and control the mouse cursor in Unity. Hiding and controlling the mouse cursor during the development of games or simulations is an important technique that helps enhance user experience. This is particularly essential when managing interactions in FPS (first-person shooter) games or with specific UI elements.

1. Overview

Hiding the mouse cursor is a straightforward process in Unity. This can increase the user’s immersion, allowing them to focus more on specific elements on the screen. To hide the cursor and implement certain functionalities, some basic script modifications and UI settings are required.

1.1. What to Expect?

Through this tutorial, we aim to achieve the following goals:

  • Understanding how to hide the mouse cursor in Unity
  • Managing mouse state with event triggers
  • Creating a user interface for cursor control
  • Adding advanced features using scripts

2. Setting Up Unity Environment

First, we need to set up a Unity project. This will proceed under the assumption that Unity is already installed.

2.1. Creating a New Project

Open Unity Hub and click the ‘New Project’ button. Here are the basic settings:

  • Project Name: MouseCursorHiding
  • Template Selection: 3D
  • Location: Set your desired location.

Then click the ‘Create’ button to generate the project.

2.2. Setting Up the Initial Scene

To set up the scene, we will add a simple 3D object. For example, add a cube or a plane.

  • In the Hierarchy window, select Right Click > 3D Object > Cube to add a cube.
  • Adjust the size of the cube to a suitable dimension and position it at the center.

3. Writing the Basic Script

We need to write a script to hide the mouse cursor. We will use C# for this.

3.1. Creating the Script

The next step is to create a new C# script.

  • In the Project window, select Right Click > Create > C# Script to create a new script.
  • Name the script CursorController.
  • Double-click on the newly created script to open it in a code editor.

3.2. Writing the Code

The code to write is as follows:

using UnityEngine;

public class CursorController : MonoBehaviour
{
    void Start()
    {
        // Hide the cursor.
        Cursor.visible = false;
        // Set the cursor lock state to center.
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        // Change the cursor state when the mouse button is clicked.
        if (Input.GetMouseButtonDown(0))
        {
            ToggleCursor();
        }
    }

    void ToggleCursor()
    {
        // Show or hide based on the current cursor state.
        if (Cursor.visible)
        {
            Cursor.visible = false;
            Cursor.lockState = CursorLockMode.Locked;
        }
        else
        {
            Cursor.visible = true;
            Cursor.lockState = CursorLockMode.None;
        }
    }
}

The above script hides the cursor and locks it in place when the game starts. When the user clicks the mouse button, it toggles the visibility of the cursor.

4. Applying the Script

You need to apply the written script to the scene.

  • Select Cube from the Hierarchy.
  • In the Inspector window, click the Add Component button and search for CursorController to add it.

Now, when you run the scene, you will see that the mouse cursor is hidden. Clicking the mouse button will make the cursor reappear.

5. Adding Advanced Features

After implementing the basic cursor hiding functionality, you can develop additional advanced features.

5.1. Integration with UI Elements

When interacting with the in-game UI, there may be a need to show the cursor. You can make it so the cursor appears when clicking on the UI.

To do this, add UI click detection to the ToggleCursor method:

using UnityEngine;
using UnityEngine.EventSystems;

public class CursorController : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    void Start()
    {
        Cursor.visible = false;
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            ToggleCursor();
        }
    }

    void ToggleCursor()
    {
        if (Cursor.visible)
        {
            Cursor.visible = false;
            Cursor.lockState = CursorLockMode.Locked;
        }
        else
        {
            Cursor.visible = true;
            Cursor.lockState = CursorLockMode.None;
        }
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        Cursor.visible = true;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Cursor.visible = false;
        Cursor.lockState = CursorLockMode.Locked;
    }
}

This will enable the cursor to be visible when hovering over UI elements and hide again when it leaves the UI.

6. Conclusion and Final Testing

Once all the above steps are completed, it’s time to build the project and conduct testing. Make sure all functions work correctly and make adjustments as needed.

6.1. Build Settings

  • In the top menu, click File > Build Settings.
  • Select the platform and click the Switch Platform button.
  • Add the necessary scenes and click the Build button to create the executable file.

6.2. Final Result Check

Run the generated executable to check if the mouse cursor hides properly, and confirm that it interacts correctly with other UI elements.

Conclusion

In this tutorial, we learned how to hide the mouse cursor in Unity. We implemented various features, from writing basic scripts to integrating with UI elements. These skills are highly useful in the development of various games and applications, so make sure to utilize them fully.

I hope you continue to gain more professional skills through various Unity-related tutorials. Thank you!

Unity Basics Course: What is an Array?

When programming in Unity, you can use various data structures. Among these, arrays are a very important data structure and are utilized in almost every part of game development. In this tutorial, we will explore the concept of arrays, how to use them, and how to leverage arrays in Unity in detail.

1. Definition of Arrays

An array is a data structure that can collectively store multiple data items of the same data type. Each element of the array can be accessed through an index, which starts from 0. For example, an array of 5 integers has indices ranging from 0 to 4.

1.1 Characteristics of Arrays

  • Fixed Size: When creating an array, you must define its size, and once set, the size cannot be changed.
  • Continuous Memory Space: The elements of the array are stored contiguously in memory.
  • Access through Index: Each element can be accessed directly through its index, allowing for quick data retrieval.

2. How to Use Arrays in Unity

In Unity, C# is primarily used, and arrays can be used to store and manage various forms of data. Below, we will learn how to declare and use arrays in Unity.

2.1 Declaring an Array

Declaring an array is simple. You define the array using the data type and square brackets.

int[] numbers; // Declaration of an integer array

2.2 Initializing an Array

After declaring an array, you must initialize it in order to use it. Initialization involves specifying the size of the array and assigning values to it.

numbers = new int[5]; // Initialize an integer array of size 5

2.3 Assigning Values to an Array

When assigning values to an initialized array, you use indices. The following example shows how to assign values to an array.

numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

You can also initialize an array with values at the time of declaration.

int[] numbers = {10, 20, 30, 40, 50};

2.4 Accessing Array Elements

Array elements can be accessed using their indices. Below is an example of accessing the first element of an array.

int firstNumber = numbers[0];  // The value of the first element is 10

2.5 Checking the Size of an Array

The size of an array can be checked using the Length property.

int length = numbers.Length; // length will be 5.

3. Types of Arrays

In Unity, arrays are classified into primitive arrays and multidimensional arrays. Let’s take a closer look at each type.

3.1 Primitive Arrays

Primitive arrays are arrays composed of values of the same data type. The most commonly used primitive arrays include the following:

  • Integer (int)
  • Floating point (float)
  • Character (char)
  • Boolean (bool)

3.2 Multidimensional Arrays

Multidimensional arrays include arrays within arrays, such as 2D and 3D arrays. For example, a 2D array can store data in a grid format.

int[,] grid = new int[3, 3]; // Declaration of a 3x3 2D array

When accessing elements in a multidimensional array, you need to specify the row and column.

grid[0, 0] = 1; // Store 1 in the first row and first column

4. Iterating and Searching in Arrays

Methods for iterating and searching through array elements are also important. You can use loops to access all elements of the array.

4.1 Iterating through an Array Using a for Loop

for (int i = 0; i < numbers.Length; i++) {
    Debug.Log(numbers[i]);
}

4.2 Iterating through an Array Using a foreach Loop

You can also use the foreach loop for a more convenient way to iterate over the elements of an array.

foreach (int number in numbers) {
    Debug.Log(number);
}

4.3 Searching an Array

To find a specific element in an array, you can use loops and conditionals. The example below shows how to search for 30 in an array.

int target = 30;
bool found = false;
for (int i = 0; i < numbers.Length; i++) {
    if (numbers[i] == target) {
        found = true;
        break;
    }
}
if (found) {
    Debug.Log("Found: " + target);
}

5. Useful Features of Arrays

Arrays are more than just a means of storing data; they can be utilized in various ways in game development. Here are a few examples of the utility of arrays.

5.1 Object Management

In Unity, you can manage game objects with arrays for batch processing. For example, when placing multiple enemies, using an array can make it more efficient.

GameObject[] enemies = new GameObject[5];
// Add enemy objects to the array
enemies[0] = enemy1;
enemies[1] = enemy2;
// ... omitted

5.2 Score System

You can also use arrays to store game scores. You can keep track of the scores for each level in an array and display them to the player.

int[] scores = new int[10]; // Scores for 10 levels

5.3 Animation Management

You can manage several animation clips in an array for easy access and transition when needed.

AnimationClip[] animations = new AnimationClip[3]; // 3 animation clips

6. Limitations and Alternatives of Arrays

While arrays are convenient, they have some limitations. You cannot dynamically change the size of an array, and you cannot store different data types together. To overcome these limitations, C# provides dynamic data structures known as collections.

6.1 Using List

The most representative collection is List. A List is similar to an array, but it can change size dynamically and can store different data types.

List numbersList = new List(); // List Declaration

6.2 Using Dictionary

Another collection frequently used in Unity is Dictionary. This structure is useful for storing data in pairs of keys and values.

Dictionary enemiesDict = new Dictionary();

7. Conclusion

Arrays are a very important element in Unity development, providing ways to efficiently manage and use data. I hope this tutorial helped you understand the basic concepts of arrays and how to use them in Unity. By utilizing arrays appropriately, you can write more efficient and organized code in game development. In the next tutorial, we will introduce more diverse data structures and algorithms.

If you encounter any issues or have questions, please leave a comment. Happy Coding!

Basic Unity Course: Player Synchronization and Controlling Only My Player Character

This course will cover how to synchronize players in multiplayer games using Unity, allowing each client to control only their player character. The course will start with the basics of network programming, explain Unity’s networking system, and discuss the client-server architecture. Additionally, we will learn how to manage and synchronize the input of each player.

1. Basic Concepts of Unity Networking

Unity provides powerful features that make it easy to develop multiplayer games. To understand the network system, you need to grasp a few basic concepts.

1.1 Client-Server Architecture

The client-server architecture is a crucial concept in network games. The client refers to the instance of the game that a player can use, while the server is the central system that manages the state of all clients.

  • Server: Manages all game progress and sends information to clients.
  • Client: Processes player inputs and progresses the game based on information received from the server.

1.2 Network Synchronization

It is essential to synchronize the states of player characters or objects in the game. That is, the same information must be provided to all clients to achieve smooth gameplay.

2. Installing Unity and Creating a Project

First, you need to install Unity and create a new project. Follow these steps:

  1. Install Unity Hub.
  2. Download and install the desired version of Unity.
  3. Click the ‘New Project’ button in Unity Hub and select either a 3D or 2D project.
  4. Choose a name and a save location for the project, then click the ‘Create’ button.

3. Setting Up the Networking Package

There are various networking libraries available in Unity, but in this course, we will use Unity’s MLAPI (Mid-Level API). Follow the steps below to install MLAPI.

  1. Open the Package Manager (Window > Package Manager) and click the ‘+’ button in the top left corner.
  2. Select ‘Git URL’ and enter https://github.com/Unity-Technologies/Mirror.git, then install it.

4. Basic Network Settings

After installing the networking package, you will need to set up the basic network settings. Follow these steps:

  1. Right-click in the Hierarchy view to add a NetworkManager object.
  2. Add the scenes you want to use in the NetworkManager’s settings menu.
  3. Add NetworkManagerHUD to set up the basic UI.

4.1 Configuring the Network Manager

Set up the NetworkManager to manage servers and clients. To achieve basic functionality, you need to be aware of the following settings:

  • Maximum Connections: Set the maximum number of clients that can connect.
  • Network Port: Set the port number that the server will use.

5. Player Settings

You need to set up each player’s character. Since the player character is directly controlled and needs to be synchronized with other clients, it should be created as a prefab.

5.1 Creating a Player Character Prefab

  1. Create a player character as a new 3D object (e.g., Cylinder).
  2. Add a Rigidbody component to the game object for movement and rotation.
  3. Create the above object as a prefab and save it in the Resources folder.

6. Writing the Player Control Script

Now, let’s write a script that will control the player character. Refer to the code below to implement the PlayerController.cs script.

using UnityEngine;
using Mirror;

public class PlayerController : NetworkBehaviour
{
    public float speed = 5f;

    void Update()
    {
        if (!isLocalPlayer)
            return;

        float moveHorizontal = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        float moveVertical = Input.GetAxis("Vertical") * speed * Time.deltaTime;

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        transform.Translate(movement);
    }
}

6.1 Script Explanation

The above script constructs a structure for controlling the player using basic WASD/arrow key inputs. It checks isLocalPlayer to ensure that only the player character of the current client can move.

7. Synchronizing Players Over the Network

The next step is to ensure that all player characters communicate with the server and synchronize. We will use SyncVar and Command to synchronize states over the network.

7.1 Setting Up SyncVar

SyncVar is used to synchronize variables over the network and automatically reflects any changes that occur on the server to the clients.

public class PlayerController : NetworkBehaviour
{
    [SyncVar]
    public Vector3 position;

    void Update()
    {
        if (!isLocalPlayer)
            return;

        float moveHorizontal = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
        float moveVertical = Input.GetAxis("Vertical") * speed * Time.deltaTime;

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        position += movement; // Update the local position
        CmdUpdatePosition(position); // Command to update the server
    }

    [Command]
    void CmdUpdatePosition(Vector3 newPosition)
    {
        position = newPosition; // Update the server's position
    }
}

8. Conclusion

In this course, we learned how to synchronize players in Unity and allow each player to control only their character. By setting up a basic network environment and scripting the players, we established the foundation for multiplayer games in Unity.

In future courses, we will add more features and increase the complexity of the game, covering more advanced topics. If you have any questions or feedback, please leave a comment!

Unity Basic Course, Making Effects for Hits

Unity Basic Course: Creating Hit Effects

Unity is a powerful engine that helps in every stage of game development. Why is it important to enhance the visual effects and interactions of a game? To emphasize these aspects, this course introduces how to create a “hit effect” using Unity. This article will explain the steps to learn the basics of Unity through a simple project and create a hit effect.

Table of Contents

  1. Setting Up the Unity Environment
  2. Modeling and Animation
  3. Projectile and Collision Handling
  4. Implementing Hit Effects
  5. Effect Optimization and Conclusion

1. Setting Up the Unity Environment

Before using Unity, you need to set up the development environment correctly. Install Unity Hub and download the latest version of Unity. When starting a new project, select the 3D template.

1.1 Creating a Project

Click ‘New’ within Unity Hub, select ‘3D’, and set the name of the project. Then click the ‘Create’ button to generate the project.

1.2 Setting Up the Basic Scene

Once the project opens, you will see a basic scene. Clear the scene and appropriately place the camera and lights. Adding a custom background is also a good idea, if needed.

2. Modeling and Animation

To implement hit effects, you first need to set up the gun and projectile models. The next steps will cover the related tasks.

2.1 Modeling the Gun

You can use a 3D modeling tool like Blender or import pre-made models. Drag and drop the gun model into the ‘Assets’ folder of the Unity project.

2.2 Creating the Projectile Model

Create a small sphere (e.g., Bullet.prefab) and adjust the scale within Unity. This model will serve as the projectile that exits the gun.

2.3 Setting Up Animation

Add the firing animation for the gun. Use the Animator to set the firing keyframes, and write a script to instantiate the projectile after the firing animation is completed.

3. Projectile and Collision Handling

Let’s learn how to create projectiles and handle collisions in Unity.

3.1 Writing the Projectile Script

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 script allows the projectile to move forward and destroy the enemy upon collision.

3.2 Setting Up Collision Layers

Set up the layers for collision detection in Unity’s Physics settings. Go to ‘Edit > Project Settings > Physics’ to configure the necessary layers.

4. Implementing Hit Effects

This section covers the steps to create effects when a bullet hits the enemy.

4.1 Adding Effect Models

Create the effect that appears when hitting an enemy. Add the effect model to the Assets folder and turn it into a Prefab.

4.2 Writing the Effect Script

using UnityEngine;

public class HitEffect : MonoBehaviour
{
    public GameObject effectPrefab;

    public void PlayEffect(Vector3 position)
    {
        GameObject effect = Instantiate(effectPrefab, position, Quaternion.identity);
        Destroy(effect, 2f); // Remove the effect after 2 seconds
    }
}

This script generates the effect and removes it after a certain amount of time.

4.3 Linking Bullet Firing and Effects

Integrate the HitEffect in the previously written Bullet script to include hit effects.

void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Enemy"))
    {
        HitEffect hitEffect = other.GetComponent();
        if (hitEffect != null)
        {
            hitEffect.PlayEffect(transform.position);
        }
        Destroy(other.gameObject);
        Destroy(gameObject);
    }
}

5. Effect Optimization and Conclusion

The final step involves optimizing the created effects and game environment to maintain smooth performance.

5.1 Effect Optimization

You can improve game performance through quality settings and memory management for the effects. Adjust the resolution and duration of the effects to reduce unnecessary memory usage.

5.2 Build and Test

Once all work is completed, build and test the project. Navigate to ‘File > Build Settings’, select the platform, and click ‘Build’ to generate the final product.

Conclusion

In this course, we explored the process of creating hit effects using Unity. I hope you learn the basics of Unity through this process and that it helps you in developing your own games. I encourage you to gradually add more complex effects and features as you progress with your personal projects!

Wishing you the best of luck in your game development journey!

Unity Basics Course: Physics Action Component

Unity is a powerful engine for creating games and simulations, offering various features. Among these, the physics components play a crucial role in realistically implementing the interactions and movements of objects within the game. In this course, we will cover the basics of Unity’s physics system, how to use the physics components, various settings, and detailed examples of game development using these components.

1. Overview of Unity’s Physics Engine

Unity’s physics engine is based on NVIDIA’s PhysX engine, supporting both 2D and 3D physics simulations. This allows for easy implementation of gravity, friction, collision handling, and developers can create realistic environments based on physical laws.

1.1. Importance of the Physics Engine

The physics engine enhances the immersion of the game and provides natural responses to player actions. For example, it is important to properly express the reactions that occur when a character collides with a wall or pushes an object.

1.2. Key Components

  • RigidBody: A component that defines the physical properties of an object. You can set properties such as mass, whether gravity is applied, and the coefficient of friction.
  • Collider: Responsible for detecting collisions between objects. It provides various types of colliders (box, sphere, mesh, etc.) for easy handling of complex shapes.
  • Physics Materials: A data type that defines the friction properties of an object. You can set surfaces to be slippery or rough.

2. RigidBody Component

RigidBody is the most important component that allows objects to interact physically. If an object does not have a RigidBody attached, it will not be affected by physics simulations and will only behave as a deformable object.

2.1. RigidBody Properties


- Mass: Sets the mass of the object. A larger mass receives more force when colliding with other objects.
- Drag: Sets the resistance felt by the object when moving through the air. A value of 0 means no resistance, and larger values increase resistance.
- Angular Drag: Sets the resistance felt by the object during rotation. It affects how quickly the rotation slows down.
- Use Gravity: By checking this option, gravity will affect the object.
- Is Kinematic: If activated, the object will not move based on the physics engine but can be displaced manually.

2.2. Applying RigidBody

Add a RigidBody component to your game object. Click the “Add Component” button in the Inspector panel of the Unity editor and select RigidBody from the “Physics” category to add it. You can adjust the default mass and gravity properties to achieve the desired physical effects.

3. Collider Component

Colliders detect collisions between objects and enable responses accordingly. The size and shape of the collider depend on the shape of the object, and careful configuration is needed for accurate collision detection.

3.1. Different Types of Colliders

Unity offers several types of colliders.

  • BoxCollider: A cuboid-shaped collider suitable for rectangular objects.
  • SphereCollider: Used for spherical objects and is the most basic form.
  • CylinderCollider: Suitable for cylindrical objects. You can set the height and radius.
  • MeshCollider: Used for objects with complex shapes. It can create a collider that matches the mesh shape exactly.

3.2. How to Use Collider

Question: How can we use colliders?
Answer: Colliders are most effective when used together with RigidBody. Add a collider to an object and, if necessary, activate the “Is Trigger” option to set it to respond when overlapping with other colliders.

4. Physics Materials

Physics Material is a data type that defines the friction properties of objects, allowing you to specify how they respond physically when coming into contact with one another.

4.1. Physics Material Properties


- Static Friction: The friction force when objects are at rest and sliding against each other.
- Dynamic Friction: The friction force applied when objects are in motion.
- Bounciness: Determines how much the object rebounds after a collision.

4.2. Creating and Applying Physics Materials

You can create a new physics material by right-clicking in the “Assets” folder in the Unity editor and selecting “Create” > “Physics Material.” After adjusting the properties of the created Material, simply drag and drop it onto the collider to apply it.

5. Example of Physics Simulations

Now, let’s proceed with a simple simulation exercise using the physics components.

5.1. Basic Terrain Setup

First, set up the terrain to be used in the 3D environment. Add a Plane for the ground and various sized cubes to create obstacles.

5.2. Player Character Setup

Next, to create the player character, add a Capsule and add the RigidBody and Capsule Collider components. Adjust the mass and property settings during this process.

5.3. Applying Physical Effects

Write a simple script to allow the player to move using the arrow keys. You can modify the velocity property of the Rigidbody to achieve movement effects.


using UnityEngine;

public class PlayerMovement : MonoBehaviour 
{
    public float speed = 10f;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent();
    }

    void Update()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        rb.velocity = movement * speed;
    }
}

6. Advanced Physics: Force and Rotation

To achieve more realistic physics effects, we will add concepts of force and rotation. In Unity, you can easily apply force and rotation to objects using the AddForce and AddTorque methods.

6.1. Applying Force

The following code shows an example of applying a continuous force to an object.


void Update()
{
    if (Input.GetKey(KeyCode.Space))
    {
        rb.AddForce(Vector3.up * 10f, ForceMode.Impulse);
    }
}

6.2. Applying Rotation

To add rotation, use the AddTorque method.


void Update()
{
    float moveHorizontal = Input.GetAxis("Horizontal");
    rb.AddTorque(Vector3.up * moveHorizontal * 10f);
}

7. Physics Debugging and Optimization

If the physics actions in your game feel unnatural, there are various methods to troubleshoot and optimize.

7.1. Using Physics Debugging Tools

You can visually verify the physics state of objects and identify problem areas using Unity’s debugging tools.

7.2. Performance Optimization

To optimize, reduce unnecessary RigidBody components and adjust the Fixed Time Step to prevent slowdowns in physics calculations.

8. Conclusion

In this course, we thoroughly explored Unity’s physics components. You can implement realistic interactions between objects through RigidBody, Collider, and Physics Material, and additionally apply forces and rotational actions. Based on this foundational knowledge, unleash your creativity to create engaging game environments.

I hope this course has helped you understand Unity’s physics components, and may you grow into a more professional game developer through continuous learning and practice.