Unity 2D Game Development, Adding Sound Background music and sound effects using Unity’s audio system.

Unity is a platform that provides powerful tools for game developers and is suitable for 2D and 3D game development. In particular, sound is an important element that makes the player’s experience meaningful when developing 2D games. This course will explain in detail how to add the necessary background music and sound effects to the game by utilizing Unity’s audio system.

1. Overview of the Audio System

Unity’s audio system provides the ability to manage and play various sounds within the game. You can control the playback and position of sounds using audio sources and audio listeners. An audio source is a component that plays sound, while an audio listener is responsible for hearing the sound. By default, the audio listener is automatically assigned to the camera.

2. Project Setup

After creating a Unity project and setting up a 2D game, you need to add sound files to the project. Various formats such as WAV, MP3, and OGG are supported for sound files. For example, it is good practice to organize background music and sound effects in separate folders.

2.1 Adding Audio Files

  1. Open the project window in the Unity Editor and right-click in the Assets folder.

  2. Select Create and then click Folder to create an Audio folder. Within this folder, create BackgroundMusic and SoundEffects folders.

  3. Drag and drop the prepared sound files into the corresponding folders.

3. Adding Background Music

To add background music, you must first set up an audio source.

3.1 Adding an Audio Source Component

  1. Create a game object. For example, select GameObject > Create Empty to create an empty game object and rename it to BackgroundMusic.

  2. Select the BackgroundMusic game object, click Add Component, and select Audio > Audio Source.

3.2 Configuring Background Music

In the component of the audio source, make the following settings:

  • AudioClip: Drag and drop the audio clip to be used as background music into this field.
  • Play On Awake: Check this option so that the background music plays automatically when the game starts.
  • Loop: Check this option to set the music to loop continuously.

3.3 Managing Background Music Using Scripts

If you want to control the background music while it is playing, you can add a script. Here’s a basic example of a C# script:

using UnityEngine;

public class BackgroundMusicManager : MonoBehaviour
{
    private AudioSource audioSource;

    void Start()
    {
        audioSource = GetComponent();
        PlayMusic();
    }

    public void PlayMusic()
    {
        if (!audioSource.isPlaying)
        {
            audioSource.Play();
        }
    }

    public void StopMusic()
    {
        if (audioSource.isPlaying)
        {
            audioSource.Stop();
        }
    }
}

4. Adding Sound Effects

Sound effects are played when specific events occur in the game. The process of adding sound effects is similar to that of adding background music, but it needs to be managed separately from the audio source.

4.1 Adding an Audio Source for Sound Effects

  1. Create a dedicated empty game object to play sound effects and name it SoundEffectsManager.

  2. Add an Audio Source to this object through Add Component.

4.2 Writing a Script to Play Sound Effects

Here’s an example of a script to play sound effects during specific events:

using UnityEngine;

public class SoundEffectsManager : MonoBehaviour
{
    private AudioSource audioSource;

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

    public void PlaySoundEffect(AudioClip clip)
    {
        audioSource.PlayOneShot(clip);
    }
}

5. Integrating with Events

Now, let’s integrate sound effects to play when specific events occur in the game. For example, we can assume that a sound effect plays when the player collects an item.

5.1 Modifying the Item Script

using UnityEngine;

public class ItemCollector : MonoBehaviour
{
    public AudioClip collectSound;
    private SoundEffectsManager soundEffectsManager;

    void Start()
    {
        soundEffectsManager = FindObjectOfType();
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            soundEffectsManager.PlaySoundEffect(collectSound);
            // Add item collection logic
            Destroy(gameObject);
        }
    }
}

6. Mixers and Audio Effects

In Unity, you can use the audio mixer to adjust the volume and panning of multiple audio sources. This allows you to create a more realistic sound environment. It is important to balance background music and sound effects using the mixer.

6.1 Creating an Audio Mixer

  1. Select Create > Audio Mixer in the project window to create a mixer.

  2. Open the mixer window and create groups called Background and Effects under Groups.

6.2 Connecting Audio Sources to the Mixer

  1. Set the Output property for the Audio Source of both background music and sound effects to connect them to the groups of the created mixer.

6.3 Adjusting Mixer Parameters

You can adjust the volume and equalizer of each group in the mixer to make the sound more unique.

7. Audio Settings for Various Platforms

Unity supports various platforms, so it is necessary to optimize audio for each platform. It is important to consider audio quality and performance on mobile devices, consoles, and PCs. You can adjust audio quality to suit each Unity platform and adjust the sound volume to ensure optimal performance.

7.1 Audio Optimization for Mobile Platforms

On mobile devices, you should reduce the size of audio files and use compressed formats (lossy compression). This helps shorten loading times and improve overall performance.

7.2 Managing Audio for PC and Console Platforms

PCs and consoles can offer higher audio quality, so you can use high-quality audio files in WAV or FLAC formats. Additionally, these platforms can utilize 3D audio to enhance user experience.

8. Conclusion and Tips

Sound is an essential element that greatly enhances immersion in a game. It is important to provide players with a memorable experience by appropriately utilizing background music and sound effects. You should select and mix sounds suitable for each genre and optimize the sound through repetitive testing.

Finally, it is important to prevent various errors that may occur during the process of adding audio and to use system resources efficiently. This can enhance the overall quality of the game.

This article explained how to add background music and sound effects using Unity’s audio system. We hope this information helps you in your game development.

2023 © Unity 2D Game Development

Unity 2D Game Development, Bug Debugging and Testing How to find and fix bugs through game testing to improve stability.

Bugs are an unavoidable element in the game development process. Especially when using powerful game engines like Unity, maintaining a high level of stability is crucial. This tutorial will explore the importance of bug debugging and testing during the Unity 2D game development process, and discuss how to find and fix bugs through game testing to enhance stability.

1. Understanding Bugs

A bug refers to an error in a program that causes it to operate incorrectly. In games, various forms of bugs can occur, such as:

  • Graphic Bugs: Instances where images are not rendered correctly or textures are applied incorrectly.
  • Logical Bugs: Cases where the behavior or rules of the game function differently than expected.
  • Performance Bugs: Situations where the frame rate drops or the game freezes.

2. What is Debugging?

Debugging is the process of identifying and fixing bugs. It can involve several steps, with the main processes being:

  1. Bug Identification: Identifying the symptoms of bugs through game testing.
  2. Bug Analysis: Investigating the causes of the bugs and analyzing where they occur.
  3. Bug Fixing: Implementing code changes to resolve the issues.
  4. Bug Revalidation: Testing the game again after fixes to confirm that the issues have been resolved.

3. Debugging Tools in Unity

Unity provides various tools and features for debugging. Here are some of them:

  • Console Window: Allows you to check error messages or warnings that occur during play.
  • Debugging Mode: A feature that allows you to observe the flow of code execution step by step and change or check variable values in real time.
  • Log Messages: You can output the state of executing code to the log using methods like Debug.Log(), Debug.LogWarning(), and Debug.LogError().

4. The Importance of Testing

Testing is the process of ensuring that the game meets its requirements. It has a significant impact on the game’s stability, performance, and user experience, so various types of testing should be conducted.

  • Functionality Testing: Verifying that each game feature operates as expected.
  • Regression Testing: Ensuring that previously fixed bugs do not reoccur.
  • Performance Testing: Measuring frame rates, loading times, memory usage, etc.
  • Reliability Testing: Testing the game to ensure it operates reliably in various environments.

5. A Simple Bug Fix Example in Unity

Below is a sample code illustrating a simple bug that can occur in Unity and its fix.


using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;

    private void Update()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        
        // Example code to move the player using Unity's MovePosition() method
        Vector3 movement = new Vector3(moveHorizontal, moveVertical, 0.0f);
        transform.position += movement * moveSpeed * Time.deltaTime;
    }
}

The above code sets the player’s movement speed and is designed to move the player based on user input. However, if the user inputs commands too quickly, the movement may behave unexpectedly. To improve this, an interpolation feature can be added.


using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    private Vector3 targetPosition;

    private void Start()
    {
        targetPosition = transform.position;
    }

    private void Update()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        
        Vector3 movement = new Vector3(moveHorizontal, moveVertical, 0.0f);
        targetPosition += movement * moveSpeed * Time.deltaTime;

        // Use interpolation to move more smoothly
        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * moveSpeed);
    }
}

In this way, debugging and fixing can enhance the quality of the game.

6. Testing Approaches: Unit Testing and Integration Testing

Testing the game’s behavior after bug fixes is essential. In Unity, you can verify code functionality through unit testing and integration testing.

6.1. Unit Testing

Unit testing is a method of checking whether specific parts of the code function as intended. Here’s a simple unit test example using the Unity Test Framework.


using NUnit.Framework;

public class PlayerMovementTests
{
    [Test]
    public void PlayerMovement_ShouldIncreasePosition_WhenInputIsGiven()
    {
        // Arrange
        GameObject playerGameObject = new GameObject();
        PlayerMovement playerMovement = playerGameObject.AddComponent();
        playerMovement.moveSpeed = 5f;
        
        // Act
        playerMovement.Move(new Vector3(1, 0, 0));

        // Assert
        Assert.AreNotEqual(Vector3.zero, playerGameObject.transform.position);
    }
}

6.2. Integration Testing

Integration testing verifies whether multiple components of the system work together. Since integration tests are conducted while the entire game’s functionality is integrated, they help enhance system compatibility.


using UnityEngine.TestTools;
using UnityEngine;

public class GameIntegrationTests : MonoBehaviour
{
    [UnityTest]
    public IEnumerator PlayerShouldReturnToStartPositionAfterDeath()
    {
        // Arrange
        GameObject playerGameObject = new GameObject();
        PlayerMovement playerMovement = playerGameObject.AddComponent();

        // Assume some method kills the player
        playerMovement.Die();

        // Act
        yield return null; // Allows the next frame to process

        // Assert
        Assert.AreEqual(Vector3.zero, playerGameObject.transform.position);
    }
}

7. Continuous Integration and Deployment (CI/CD)

Utilizing CI/CD processes can enable faster and more reliable application deployment. CI is the process of automatically running tests upon code changes, while CD refers to automated deployment.

This way, only tested code can be deployed, enhancing the quality of the game. Tools like Jenkins and Travis CI can be used to integrate CI/CD into Unity projects.

8. The Importance of Player Feedback

Collecting player feedback as part of game testing is extremely important. Players can report bugs or usability issues that may not be discovered through actual gameplay. Therefore, releasing the game in a beta testing format to gather feedback is advisable.

9. Conclusion

Bug debugging and testing are crucial processes in Unity 2D game development. Through the right tools and methodologies, you can enhance the quality and stability of your game. Continuous improvement can ultimately result in better games.

This tutorial reviewed understanding bugs, debugging methods, debugging tools in Unity, the importance of testing, and both unit testing and CI/CD. In your future development processes, leverage this knowledge to create more stable and enjoyable games.

Unity 2D Game Development, Implementing Multiplayer Features: How to Add Simple Multiplayer Features to a 2D Game.

Introduction

In this course, we will learn how to add simple multiplayer features to a 2D game using the Unity engine.
Multiplayer functionality greatly increases the fun of the game and provides opportunities to enjoy it with friends.
Additionally, through the process of implementing multiplayer, you will understand concepts such as networking and data synchronization.

1. Preparing the Game

First, let’s conceptualize the game you want to create.
For example, a simple 2D platformer.
Players can compete against each other to earn points or achieve objectives.

1.1 Creating a Unity Project

After launching Unity, create a new 2D project.
Name the project ‘Multiplayer2DGame’ and select the default template.

2. Setting Up Photon Unity Networking (PUN)

We will use a library called Photon Unity Networking (PUN) to implement multiplayer features.
PUN is a tool that simplifies multiplayer game development in Unity.

2.1 Installing PUN

3. Implementing Basic Player

Now let’s create a basic player character. The player should be able to interact with other users.
We need to create a player prefab and set up network synchronization using PUN.

3.1 Creating a Player Prefab

  1. Create the player character using a 2D sprite. For example, let’s create a circular sprite.
  2. Create a new Empty GameObject and name it ‘Player.’
  3. Add Circle Collider 2D and Rigidbody 2D components to the Player GameObject.
  4. Now, make the Player a Prefab and save it in the Assets folder.

3.2 Integrating with PUN

Create a player script to integrate PUN functionalities. Let’s write the player script using the code below.

using UnityEngine;
using Photon.Pun;

public class PlayerController : MonoBehaviourPunCallbacks
{
    public float moveSpeed = 5f;

    void Update()
    {
        if (photonView.IsMine)
        {
            Move();
        }
    }

    void Move()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        Vector3 moveDirection = new Vector3(horizontal, vertical, 0).normalized;
        transform.position += moveDirection * moveSpeed * Time.deltaTime;
    }
}

3.3 Player Spawning

Next, we need to add functionality to spawn the player when the game starts.
Add the code below to a new script called GameManager.

using UnityEngine;
using Photon.Pun;

public class GameManager : MonoBehaviourPunCallbacks
{
    void Start()
    {
        PhotonNetwork.ConnectUsingSettings();
    }

    public override void OnConnectedToMaster()
    {
        PhotonNetwork.JoinLobby();
    }

    public override void OnJoinedLobby()
    {
        PhotonNetwork.LoadLevel("GameScene");
    }

    public override void OnJoinedRoom()
    {
        PhotonNetwork.Instantiate("Player", Vector3.zero, Quaternion.identity, 0);
    }
}

4. Implementing Game Lobby

A multiplayer game requires a lobby. In the lobby, players can wait and start the game.
Let’s move on to creating the lobby UI.

4.1 Setting Up UI

We will use Unity’s UI system to create the UI.
Create a Canvas and add button and text UI elements.
Buttons can perform functions like ‘Create Room’ and ‘Join Room.’

4.2 Adding Room Creation and Joining Code

using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;

public class LobbyManager : MonoBehaviourPunCallbacks
{
    public InputField roomNameInputField;
    
    public void CreateRoom()
    {
        string roomName = roomNameInputField.text;
        RoomOptions roomOptions = new RoomOptions() { MaxPlayers = 4 };
        PhotonNetwork.CreateRoom(roomName, roomOptions);
    }

    public void JoinRoom()
    {
        string roomName = roomNameInputField.text;
        PhotonNetwork.JoinRoom(roomName);
    }

    public override void OnCreatedRoom()
    {
        Debug.Log("Room has been created.");
    }

    public override void OnJoinedRoom()
    {
        Debug.Log("Joined the room.");
    }
}

5. Network Synchronization

Now we will implement network synchronization so that multiple players can connect to the game and interact with each other.
We will synchronize player actions using Photon.

5.1 Using RPC

We will use RPC (Remote Procedure Call) to synchronize player actions (e.g., jumping, attacking, etc.).
Below is the code that will be used when the player jumps.

using Photon.Pun;

[PunRPC]
public void Jump()
{
    if (IsGrounded())
    {
        GetComponent().AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
    }
}

6. Implementing Scoring System

In cases where multiple players compete against each other, a scoring system is needed.
This system is responsible for storing and displaying players’ scores.

6.1 Creating Score Database Class

using UnityEngine;

[System.Serializable]
public class PlayerScore
{
    public string playerName;
    public int score;
}

public class ScoreManager : MonoBehaviour
{
    public List scores = new List();
}

6.2 Displaying Scores

In order to display the scores in the UI, we will create a Text UI element and make a script that updates each player’s score.

using UnityEngine;
using UnityEngine.UI;

public class ScoreDisplay : MonoBehaviour
{
    public Text scoreText;

    public void UpdateScore(PlayerScore playerScore)
    {
        scoreText.text = playerScore.playerName + ": " + playerScore.score;
    }
}

7. Testing and Deployment

After implementing all the features, we will perform testing.
Use PUN’s Premier Servers to run multiple clients and check progress and bugs.
After testing is complete, the game can be built and distributed to users.

Conclusion

In this course, we learned how to add multiplayer features to a 2D game in Unity.
Utilizing Photon Unity Networking (PUN), we were able to facilitate interactions and data synchronization among players.
Developing a multiplayer game is not easy, but it is a very interesting and rewarding task.
I hope you can add various features and create your own game in your personal style.
Stay tuned for more Unity-related courses!

Unity 2D Game Development, Implementing Leaderboard System Build a leaderboard that saves player scores and allows competition with users around the world.

Today, we will learn how to build a leaderboard system, which is one of the essential features in Unity 2D game development. Leaderboards are important elements that record player scores and promote competition among users. In this article, we will explain the entire process and key codes required to implement a leaderboard system step by step.

What is a Leaderboard System?

A leaderboard system is an interface that stores the scores of game players on a cloud server and displays them for users to view. This system enhances the competitiveness of the game and increases players’ sense of achievement.

Purpose of Implementing a Leaderboard System

  • Allows recording and management of player scores.
  • Enables comparison of one’s score with other players worldwide.
  • Enhances players’ sense of achievement and encourages them to challenge the game again.

Contents Covered in This Article

  1. Overview of Leaderboard System Design
  2. Data Storage through Integration with Cloud Firestore
  3. Building Leaderboard UI in Unity
  4. Implementing Leaderboard Score Update and Query Functions
  5. Final Summary and Additional Considerations

1. Overview of Leaderboard System Design

To design a leaderboard system, we first need to define the data structure. Typically, a leaderboard includes player names, scores, play time, and so on. For example, we can design the data in the following format:


{
    "leaderboard": [
        {
            "playerName": "Player1",
            "score": 1000,
            "time": "2023-10-01T10:00:00Z"
        },
        {
            "playerName": "Player2",
            "score": 900,
            "time": "2023-10-01T09:30:00Z"
        }
    ]
}

2. Data Storage through Integration with Cloud Firestore

Before implementation, let’s look at how to save and manage scores using Firebase and Firestore services. Firebase helps to securely store leaderboard data and retrieve it easily. Follow the steps below to create a Firebase project and set up Firestore.

2.1 Create a Firebase Project

  1. Visit the Firebase Console and create a new project.
  2. After creating the project, enable the Firestore database.
  3. Select Cloud Firestore and proceed to create the database.

2.2 Install Firebase SDK in Unity

  1. Download the Unity SDK from the official Firebase website.
  2. Add the Firebase package to the Unity project and install the necessary modules.
  3. Ensure to check the Firestore module to use leaderboard features.

2.3 Set Firestore Data Structure

Set the database structure to be used in Firestore. Create a collection named ‘leaderboard’ and create documents to store player scores within it.

3. Building Leaderboard UI in Unity

To implement the leaderboard feature, set up the UI. You can design the user interface using Unity’s Canvas.

3.1 Add UI Components

  1. Create a Canvas. (GameObject > UI > Canvas)
  2. Add a Text UI element for the leaderboard title.
  3. Add a Scroll View to display scores in a list format.
  4. Place a Text UI element within the Scroll View to display each player’s score.

3.2 Write a Script to Display Scores


using UnityEngine;
using UnityEngine.UI;
using Firebase.Firestore;
using System.Collections.Generic;

public class LeaderboardManager : MonoBehaviour
{
    public Text leaderboardTitle;
    public Transform contentParent;
    public GameObject scoreEntryPrefab;

    private FirebaseFirestore db;

    void Start()
    {
        db = FirebaseFirestore.DefaultInstance;
        LoadLeaderboard();
    }

    void LoadLeaderboard()
    {
        db.Collection("leaderboard").OrderBy("score", descending: true).Limit(10).GetSnapshotAsync().ContinueWith(task =>
        {
            if (task.IsCompleted)
            {
                foreach (var document in task.Result.Documents)
                {
                    string playerName = document.GetValue("playerName");
                    long score = document.GetValue("score");
                    DisplayScore(playerName, score);
                }
            }
        });
    }

    void DisplayScore(string playerName, long score)
    {
        GameObject entry = Instantiate(scoreEntryPrefab, contentParent);
        entry.GetComponent().Setup(playerName, score);
    }
}

4. Implementing Score Update and Query Functions for the Leaderboard

Now, let’s implement the functionality to update and query player scores. To do this, we will write a method to record scores and call this method when a player’s score updates in the game.

4.1 Add Score Update Method


public void UpdateScore(string playerName, long score)
{
    DocumentReference docRef = db.Collection("leaderboard").Document(playerName);
    docRef.SetAsync(new { playerName = playerName, score = score }, SetOptions.MergeAll);
}

4.2 Call Score Update in the Game

In the game, call the above method to update the score when a player earns points or when the game ends.


void EndGame()
{
    UpdateScore(playerName, currentScore);
}

5. Final Summary and Additional Considerations

In conclusion, we have explained how to implement a leaderboard system in Unity 2D games. This system is a very important feature that promotes competition among players and adds excitement to the game.

Additionally, you may consider adding various filtering features (for example, weekly, monthly rankings) to the leaderboard, or implementing a reward system for players. By evolving the leaderboard system in such ways, you can significantly enhance the user experience.

I hope this article has helped with Unity game development, and if you have any questions or additional topics you’d like to see, please leave a comment!

Unity 2D Game Development, Add Advertising and In-App Purchases Add advertising and in-app purchase features using Unity Ads and IAP.

Recently, 2D games have become very popular, and many developers are using Unity to develop their games. Unity provides a powerful engine and various tools to help developers implement their creative ideas into actual games. However, just developing a game is not enough to generate revenue. Therefore, it is important to add advertising and in-app purchase features. This article will detail how to add advertising and in-app purchase features using Unity Ads and Unity IAP (In-App Purchase).

1. Overview of Unity Ads

Unity Ads is an advertising platform provided by the Unity engine, allowing developers to easily integrate ads into their games. Through Unity Ads, developers can display ads to generate revenue without interrupting the user’s gaming experience.

2. How to Set Up Unity Ads

To set up Unity Ads, the following steps are required.

2.1 Setting Up a Unity Project

To use the Ads feature in the Unity project, you first need to enable the Ads service in your Unity project. Select Window > General > Services from the top menu of the Editor. In the Unity Services window, select “Ads” and enable it. You will need to log in to your Unity developer account to do this.

2.2 Setting Up Advertising

Once the service is activated, an Ads ID will be created for the project. This information can be used to integrate Unity Ads.

2.3 Importing the Unity Ads SDK

Open the Unity Package Manager and find the Ads package in the Unity Registry to install it. This will add the packages related to Unity Ads to the project.

3. Unity Ads Code Sample

The basic code to integrate Unity Ads into a game is as follows.

using UnityEngine;
using UnityEngine.Advertisements;

public class AdsManager : MonoBehaviour, IUnityAdsListener
{
    private string gameId = "YOUR_GAME_ID";
    private bool testMode = true;
    
    void Start()
    {
        if (Advertisement.isSupported)
        {
            Advertisement.Initialize(gameId, testMode);
            Advertisement.AddListener(this);
        }
    }

    public void ShowAd()
    {
        if (Advertisement.IsReady("video"))
        {
            Advertisement.Show("video");
        }
    }

    public void OnUnityAdsReady(string placementId) { }

    public void OnUnityAdsDidFinish(string placementId, ShowResult showResult) 
    {
        if (showResult == ShowResult.Finished)
        {
            // Action when ad is fully viewed
            Debug.Log("Ad viewing completed");
        }
        else if (showResult == ShowResult.Skipped)
        {
            // In case the ad was skipped
            Debug.Log("Ad skipped");
        }
        else if (showResult == ShowResult.Failed)
        {
            // Ad load failed
            Debug.Log("Ad load failed");
        }
    }

    public void OnUnityAdsDidError(string message) 
    {
        Debug.Log("Ad error occurred: " + message);
    }
}
        

4. Overview of In-App Purchases (IAP)

In-app purchases allow users to buy items or features within the game. Using IAP in Unity makes it easy to implement such features.

5. How to Set Up Unity IAP

The steps for installing and setting up Unity IAP are as follows.

5.1 Importing the Unity IAP Package

In the Unity editor, select Window > Package Manager and find the Unity IAP package to install it.

5.2 Activating Services

To use IAP, you must activate the IAP service in Unity Services. Select “IAP” in the Services window and enable it.

5.3 Registering Products

You need to register products (in-app purchase items) in the Unity dashboard. You must set a unique ID and specify a price for each product. This information can be used in your code.

6. Unity IAP Code Sample

The basic code for integrating Unity IAP and handling in-app purchases is as follows.

using UnityEngine;
using UnityEngine.Purchasing;

public class IAPManager : MonoBehaviour, IStoreListener
{
    private static IStoreController m_StoreController;          
    private static IExtensionProvider m_ExtensionProvider;
    
    public string productId = "YOUR_PRODUCT_ID";

    void Start()
    {
        if (m_StoreController == null)
        {
            InitializePurchasing();
        }
    }

    public void InitializePurchasing()
    {
        if (IsInitialized())
            return;

        var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
        builder.AddProduct(productId, ProductType.Consumable);
        UnityPurchasing.Initialize(this, builder);
    }

    private bool IsInitialized()
    {
        return m_StoreController != null && m_ExtensionProvider != null;
    }

    public void BuyProductID()
    {
        BuyProductID(productId);
    }

    void BuyProductID(string productId)
    {
        BuyProduct(productId);
    }

    public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
    {
        m_StoreController = controller;
        m_ExtensionProvider = extensions;
        Debug.Log("Purchase initialization completed");
    }

    public void OnInitializeFailed(InitializationFailureReason error)
    {
        Debug.Log("Purchase initialization failed: " + error.ToString());
    }

    public void OnPurchaseFailed(Product product, PurchaseFailureReason reason)
    {
        Debug.Log($"Purchase failed: {product.definition.id}, Reason: {reason}");
    }

    public void OnPurchased(Product product)
    {
        Debug.Log($"Purchase completed: {product.definition.id}");
    }

    public void OnPurchasingFailed(Product product, PurchaseFailureReason reason)
    {
        Debug.Log($"Error occurred during purchase: {product.definition.id}, Reason: {reason}");
    }
}
        

7. Final Check for Integrating Ads and In-App Purchases into the Game

Now that you have integrated Unity Ads and IAP, you can display ads within the game and perform in-app purchases. It is important to provide appropriate feedback when users view ads or make purchases.

8. Conclusion

Through this article, we have learned how to add advertising and in-app purchase features to Unity 2D games. Proper use of Unity Ads and IAP can enhance the profitability of the game. However, excessive advertising can harm user experience, so it is important to maintain a proper balance. Create great 2D games with Unity!