[Introduction to Unity2D Game Development Volume 3] ✨Introduction to Unity Summary Sunnyland Example (Volume 2)

✨✨Contents










1. Introductory Volume [Volume 2]

back to the top

  1. Simple UI

  2. main menu

  3. pause menu

  4. Android test game (touch operation)

  5. game generation

[Getting started] 12. Simple UI

A. Add Text

An older version of Text is used here

Create text on previous canvas

Change the properties, set the anchor point here to adapt to different resolutions

Adjust text to center, set text

Ctrl + D Copy a copy of Text as the record of the number of collections

B. Sample code

Create a new script UI_CollectionNum.cs

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

public class UI_CollectionNum : MonoBehaviour
{
    // --- public --------------------------------------
    public Text m_TextCollectionNum;
    public PlayerController m_Player;

    // --- private -------------------------------------
    private void Update()
    {
        m_TextCollectionNum.text = m_Player.m_CollectionsCount.ToString();
    }
}

I like the dark purple background so I changed the text color to white
You can set a lot of attributes here, try it yourself, so that you will be impressed
After you try it, you will find that it is quite simple

C. Section example










[Getting Started] 13. Game start main menu

A. Create a new scene

Create a new scene and name it MainMenu

B. Setting the canvas panel background

Here the background is set to None to ensure full fill

Maybe you will find that the game screen is not completely black (even if you make the color black, maybe you forgot to set the transparency? Small pit)

You can also capture a picture, here I capture a picture of scene 2 as the background picture of the panel

Rename the panel to BG

C. Set the canvas panel button

Add another panel and rename it MainMenu

Let's add some buttons on it

May allow you to import some extension packs, here I imported both

Property settings you can adjust appropriately

probably so

Make another copy and change the text to "Button"

D. Set the title

E. Add script

Add the C# script MainMenu.cs

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

public class MainMenu : MonoBehaviour
{
    /// <summary>
    /// @brief start the game
    /// </summary>
    public void PlayGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); 
    }

    /// <summary>
    /// @brief exit game
    /// </summary>
    public void QuitGame()
    {
        // Both of the following are fine
        //Application.Quit(); // This will only work if the game is released
        UnityEditor.EditorApplication.isPlaying = false;  // use this
    }
}

Here hang the script MainMenu on the MainMenu object, click the button, and there is On Click under the Button component of the button

You can call the function when it is clicked, drag the MainMenu object in, and select the script we added

Now you can run the game to test [Don't forget to set the Build Index of the scene in BuildSettings]

Let’s add a gradient animation, here you can adjust the Samples appropriately, and then uncheck the animation cycle (click on the anim file to see it)

Let the animation finish playing before displaying text and buttons

Create an empty object manager

Add code in MainMenu

/// <summary>
/// @brief activates the UI, showing
/// </summary>
public void ShowUI()
{
    GameObject.Find("Canvas/MainMenu/UI").SetActive(true);
}

Ok, then the menu scene is complete

F. Section presentation










[Getting started] 14. Pause menu

A. Setup UI

In the first scene, we add a pause button to the canvas

If you want to input Chinese, one of the ways is to create a Chinese font

Create another canvas as the page that pops up from the menu. This color is random, and I am only doing a demonstration

Create a slider and set the color of the slider

change fill color

B. Add script

Create GamePauseMenu.cs

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

public class GamePauseMenu : MonoBehaviour
{
    // --- public ----------------------------------------------
    public Slider m_Slider;  // Slider to control volume
    public GameObject Panel_PauseMenu;

    /// <summary>
    /// @brief pause game
    /// </summary>
    public void OnClickPause()
    {
        Panel_PauseMenu.SetActive(true);
        Time.timeScale = 0.0f;
    }

    /// <summary>
    /// @brief resume game
    /// </summary>
    public void OnClickResume()
    {
        Panel_PauseMenu.SetActive(false);
        Time.timeScale = 1.0f;
    }

    /// <summary>
    /// @brief exit game
    /// </summary>
    public void OnClickQuit()
    {
        UnityEditor.EditorApplication.isPlaying = false;
    }
}

Don't forget to add a function to the button, it's the same as before

C. Slide bar to adjust volume

There are many ways to adjust the volume, here is one that I often use

Note that there is an Output here, which requires Audio Mixer

Window -> Audio -> Audio Mixer

Click Add and rename to MainMixer

You can create it manually, if I open the Audio Mixer panel to add it will be automatically created in the project directory

Then double-click to open the panel

Now, set the Output of all Audio Source s to MainMixer and associate them

It may not be possible to drag and drop directly. You need to click the button on the right to set and specify the Mixer. It should be very simple, mainly because you are familiar with the process

Adjust the value of the slider here

Need to create a parameter

Add script in GamePauseMenu.cs

using UnityEngine.Audio;

public AudioMixer m_MainMixer;

/// <summary>
/// @brief adjust the volume
/// </summary>
/// <param name="value"></param>
public void OnChangedVolume(float value)
{
    m_MainMixer.SetFloat("MasterVolume", value);
}

private void Start()
{
    // Set the volume first at the beginning, otherwise it will not be refreshed at the beginning, and the volume will suddenly change if you suddenly adjust the volume
    m_MainMixer.SetFloat("MasterVolume", -15.0f);
}

Set the function for the slider

GamePauseMenu.cs complete code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;

public class GamePauseMenu : MonoBehaviour
{
    // --- public ----------------------------------------------
    public Slider m_Slider;  // Slider to control volume
    public GameObject Panel_PauseMenu;
    public AudioMixer m_MainMixer;  // MainMixer

    /// <summary>
    /// @brief pause game
    /// </summary>
    public void OnClickPause()
    {
        Panel_PauseMenu.SetActive(true);
        Time.timeScale = 0.0f;
    }

    /// <summary>
    /// @brief resume game
    /// </summary>
    public void OnClickResume()
    {
        Panel_PauseMenu.SetActive(false);
        Time.timeScale = 1.0f;
    }

    /// <summary>
    /// @brief exit game
    /// </summary>
    public void OnClickQuit()
    {
        UnityEditor.EditorApplication.isPlaying = false;
    }

    /// <summary>
    /// @brief adjust the volume
    /// </summary>
    /// <param name="value"></param>
    public void OnChangedVolume(float value)
    {
        m_MainMixer.SetFloat("MasterVolume", value);
    }

    private void Start()
    {
        // Set the volume first at the beginning, otherwise it will not be refreshed at the beginning, and the volume will suddenly change if you suddenly adjust the volume
        m_MainMixer.SetFloat("MasterVolume", -15.0f);
    }
}

Ok, now the menu function is complete, you can try it, and then you can add more functions










[Getting Started] 15. Android test game (touch operation)

A. Mobile phone test

Here is a demonstration of the Android platform

file -> build settings

Switch to the Android platform, if you don’t install it, you need to install it on Android

To connect the data cable, you may need to check the options, check them all, and then switch the device

Now run the game and you should be able to see the synchronization on the phone

B. Touch operation

Add this plugin, ✨Unity Asset Store can be found

PlayerController.cs mobile changes

/// <summary>
/// @brief horizontal movement
/// </summary>
private void HorizontalMove()
{
    // Get horizontal input [-1, 1], 0 when key is released
    //float horizontalValue = Input.GetAxis("Horizontal");
    float horizontalValue = m_Joystick.Horizontal;  // Mobile touch remote control
    
    // ...

PlayerController.cs changes

[Header("Mobile phone touch operation")]
public Joystick m_Joystick;
public bool m_BClickJump = false;

/// <summary>
/// @brief detection status
/// </summary>
private void CheckState()
{
    // to run
    m_BAnimRunning = (Mathf.Abs(m_Rb.velocity.x) > 0.1f && !m_BAnimCrouching && !m_BAnimJumping && !m_BAnimFalling);
    // whereabouts
    m_BAnimFalling = m_Rb.velocity.y < -0.1f;
    // jump
    if ((m_BOnGround && (m_BDoJump || m_BClickJump)) || (!m_BOnGround && m_AllowAirJumpCount > 0 && (m_BDoJump || m_BClickJump)))
    {
        m_BAnimJumping = true;
    }
    else if (m_BAnimFalling)
    {
        m_BAnimJumping = false;
    }
    // squat down
    m_BAnimCrouching = (m_BOnGround && ((m_BPressedCrouch && (!m_BAnimJumping || !m_BAnimFalling)) || m_BTopHasWall));
    // idle
    m_BAnimIdling = (m_BOnGround && !m_BAnimCrouching && !m_BAnimFalling);
}

/// <summary>
/// @brief jump
/// </summary>
private void Jump()
{
    if (m_BOnGround && (m_BDoJump || m_BClickJump))
    {
        m_BDoJump = false;
        m_BClickJump = false;
        m_Rb.velocity = new Vector2(m_Rb.velocity.x, m_JumpSpeedPerSecond * Time.fixedDeltaTime);
        // play sound
        AudioManager.GetInstance().PlayJumpAudio();
    }
    if (!m_BOnGround && m_CurrentAllowAirJumpCount > 0 && (m_BDoJump || m_BClickJump))
    {
        // air jump
        m_BDoJump = false;
        m_BClickJump = false;
        --m_CurrentAllowAirJumpCount;
        m_Rb.velocity = new Vector2(m_Rb.velocity.x, m_JumpSpeedPerSecond * Time.fixedDeltaTime);
        // play sound
        AudioManager.GetInstance().PlayJumpAudio();
    }
}

GamePasueMenu

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;

public class GamePauseMenu : MonoBehaviour
{
    // --- public ----------------------------------------------
    public Slider m_Slider;  // Slider to control volume
    public GameObject Panel_PauseMenu;
    public AudioMixer m_MainMixer;  // MainMixer
    public PlayerController m_Player;

    /// <summary>
    /// @brief pause game
    /// </summary>
    public void OnClickPause()
    {
        Panel_PauseMenu.SetActive(true);
        Time.timeScale = 0.0f;
    }

    /// <summary>
    /// @brief resume game
    /// </summary>
    public void OnClickResume()
    {
        Panel_PauseMenu.SetActive(false);
        Time.timeScale = 1.0f;
    }

    /// <summary>
    /// @brief exit game
    /// </summary>
    public void OnClickQuit()
    {
        UnityEditor.EditorApplication.isPlaying = false;
    }

    /// <summary>
    /// @brief adjust the volume
    /// </summary>
    /// <param name="value"></param>
    public void OnChangedVolume(float value)
    {
        m_MainMixer.SetFloat("MasterVolume", value);
    }

    private void Start()
    {
        // Set the volume first at the beginning, otherwise it will not be refreshed at the beginning, and the volume will suddenly change if you suddenly adjust the volume
        m_MainMixer.SetFloat("MasterVolume", -15.0f);
    }

    /// <summary>
    /// @brief Press the jump button
    /// </summary>
    public void OnClickJump()
    {
        m_Player.m_BClickJump = true;
    }
}

You can try it now, and then you can add more functions, such as jumping with keys

C. Section presentation










[Getting Started] 16. Game generation

Take the Android platform as an example

You can also set the project settings

Select the platform, Build

Build may have a small pit, the previous code

This cannot be used on the Android platform, just use the first one

UnityEditor.EditorApplication.isPlaying = false;  // use this
/// <summary>
/// @brief exit game
/// </summary>
public void QuitGame()
{
    // Both of the following are fine
    Application.Quit();  // This will only work if the game is released
    //UnityEditor.EditorApplication.isPlaying = false; // Use this
}

There should be two places to be changed, both of which should be changed to the first method to export normally

There is another one, the main scene UI, other UI can be adjusted by yourself

Set default portrait rotation










2. Miscellaneous Volume

[Miscellaneous Volume] 1. Changing the canvas UI to a prefab does not work when switching scenes

This is still a basic question

Probably you forgot EventSystem

Just add an EventSystem










Three, finally

So, this is the end of the Sunnyland example. In fact, there are still many problems in the Android platform, and a separate module introduction will be released later.

The End.

Tags: C# Unity Game Development UI

Posted by anoopd on Wed, 14 Dec 2022 20:57:39 +1030