Change Control By Pressing A Button Using C# Script In Unity

Introduction

In this article, I will explain how to create change controls by pressing a button using C# Script in Unity 3D.

Prerequisites

Unity Environment version 2020.1.0a25.3171

Create the project

Create a new project. After that, we will drag an asset, so as to texture the floor

Click on the "GameObject" menu in the menu bar. Select UI objects and pick the "Canvas" option. The canvas will be added to the scene view.

To add a text to the canvas, select Canvas and then select text

So let's set up the screen. Double click on canvas so we can see what we're working with here. I just click the 2d here instead of the regular 3d view.

The first text here, let's call it menu screen. Now I will increase the font size and position the menu screen text at the top, following the steps given in the image.

Then over here click menu screen text to open inspector -> rect transform, then press the alt key to change it to the docking. I'll dock the menu screen up to the top

Create the Button

If a canvas is already present in the Hierarchy, right-click the canvas and select UI > Button. Create two buttons.

Rename the Button as ButtonKeyboard & ButtonMouse in Scene View

Let's change the text on the button keyboard to say "keyboard "

Change the text on the button mouse to say "mouse "

I'll move the keyboard up from the centerline and then I'll select the mouse button. Click alt to make both the buttons centered, then move it down from the centerline.

I have created a new text, that I'll add in and this would be the text control type to show text, then move it down from the centerline. Let's make the font a little bigger maybe 20. We will set vertical and horizontal overflow to overflow.

Now you pick either a keyboard or mouse that you want to play, you have to press the button to actually play.

Let's add more buttons to play. For that click Hierarchy and go to Create → UI → Button, and call/rename it to "button play" and the text for it will "playing". Select the button and move it down.

Create a C# Script

Right-click on Assets. Select Create >> C# script.

Rename the script as Menu Screen

Double click on Scene One and it will open Visual Studio 2019, which is my programming integrated development environment (IDE) for Unity. Write the code as shown below:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MenuScreen: MonoBehaviour {
    public static int ControlType = 1;
    public static string SetControlType_GetDesc(int type) {
        ControlType = type;
        switch (ControlType) {
            case 1:
                return "Keyboard";
            case 2:
                return "Mouse";
            default:
                return ControlType.ToString();
        }
    }
}

Save the program

Let's make a new script. Right-click on Assets. Select Create >> C# script.

Then we're going to put the script of this button here on the canvas

Double click on Scene One and it will open Visual Studio 2019, which is my programming integrated development environment (IDE) for Unity. Write the code as shown below:

using UnityEngine;
using UnityEngine.AI;
public class Player: MonoBehaviour {
    public float Movespeed = 3.5 f;
    public NavMeshAgent nma = null;
    private void Update() {
        switch (MenuScreen.ControlType) {
            case 1:
                Keyboard();
                break;
            case 2:
                Mouse();
                break;
        }
    }
    private void Keyboard() {
        nma.ResetPath();
        if (Input.GetKey(KeyCode.W) == true) {
            this.transform.Translate(Vector3.forward * Movespeed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.S) == true) {
            this.transform.Translate(Vector3.back * Movespeed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.A) == true) {
            this.transform.Translate(Vector3.left * Movespeed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.D) == true) {
            this.transform.Translate(Vector3.right * Movespeed * Time.deltaTime);
        }
    }
    private void Mouse() {
        if (Input.GetMouseButtonDown(0) == true) {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit) == true) {
                nma.SetDestination(hit.point);
            }
        }
    }
}

Save the program

Select the Keyboard button and with the keyboard, button selected I scroll down here to the On Click () and I can tell it what to do on click, so let me add something for it to do.

It's the canvas object. now in the canvas object, I can pick buttons. Now we will call the on Canvas using the keyboard button from my Buttons script.

We will be doing the same thing as we did for keyboard button with the Mouse button.

Start this game by clicking on the Play button. We will get the output based on the button we press.

It will say keyboard if the keyboard button is pressed.

I press the mouse button, which outputs "Mouse"

Create a new scene from the File menu: (File > New Scene) let's save this scene in the scene folder, we'll call this one "game".

The game scene just add something like a floor. Right-click on the Hierarchy window and choose 3D Object > Cube

Rename the cube as floor and set the transform. and let's drag and drop floor texture on a cube

Add a player to a game object. rename the cube as Player and set the transform.

Let's give the player a different color, so we create a new material.

Select the player material and let's give it red color.

Drag and drop the materials to player.

Create a new script. Right-click on Assets. Select Create >> C# script

Rename the script as Player, we'll drag and drop that on the Player.

Double click in Scene One and it will open Visual Studio 2019, which is my programming integrated development environment (IDE) for Unity. Write the code as shown below,

using UnityEngine;
using UnityEngine.AI;
public class Player: MonoBehaviour {
  public float Movespeed = 3.5 f;
  public NavMeshAgent nma = null;
  private void Update() {
    switch (MenuScreen.ControlType) {
    case 1:
      Keyboard();
      break;
    case 2:
      Mouse();
      break;
    }
  }
  private void Keyboard() {
    nma.ResetPath();
    if (Input.GetKey(KeyCode.W) == true) {
      this.transform.Translate(Vector3.forward * Movespeed * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.S) == true) {
      this.transform.Translate(Vector3.back * Movespeed * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.A) == true) {
      this.transform.Translate(Vector3.left * Movespeed * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.D) == true) {
      this.transform.Translate(Vector3.right * Movespeed * Time.deltaTime);
    }
  }
  private void Mouse() {
    if (Input.GetMouseButtonDown(0) == true) {
      RaycastHit hit;
      Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      if (Physics.Raycast(ray, out hit) == true) {
        nma.SetDestination(hit.point);
      }
    }
  }
}

Save the program

Add a navmesh from the navmesh window.

We have a navigation window, I go to bake and it's going to bake all static objects with a navmesh on them, so let's make sure that the floor is static, then we go to bake navigation and, we press bake real quickly, it makes this blue area.

On the player, let me select the player, and here's the inspector. I'm just going to add a navmesh agent component which will be in the navigation nav mesh agent

Select the player and the script right here, since we want to know what the navmesh agent is? so let's just drag this and drop it to the player script

We have to go to the build settings, so let's go to file build settings and we're going to have the menu screen first, and then we're going to have the game scene

Open the menu scene, view the canvas here we have to select the play button, so we could go to the game screen. let's connect the button click event to the button, so I select the button to play and here on the on click (). I put the button script on canvas and then from the button script I want to do button play click

So let me add a canvas here. Click on the "GameObject" menu in the menu bar. Select UI objects and pick the "Canvas" option. The canvas will be added to the scene View

Select the canvas and add the buttons again, so I will create a button for the keyboard and play button.

Let's change this text on the keyboard.

Change the text on the mouse.

Select the button script and; drag and drop it on this canvas

The first button is the keyboard and we're going to call the script on the canvas, i.e. the button's script, and click the keyboard.

Select the button mouse text, we'll call the script on the canvas and Click mouse button.

Now, where are the buttons? let's have a look at the game view, so right now they are in the middle. Let's select the keyboard button, and set the position using the Alt Key, and put it in the top corner.

Similarly, we will move the mouse button down.

Select the control type, to show the text on the screen. Rename text as "Text control type". So let's select the "Textcontroltype" and set the position using the Alt Key, and put it in the top corner. We will move the text button down. and make the font a little bigger maybe 20. We will set vertical and horizontal overflow to overflow.

Start the game scene, go to the menu screen. Press the play button. Let's make sure the mouse and keyboard button works, by clicking the button.

The below image shows that the mouse button work.

Similarly, we will check for the keyboard button.

The below image shows that the keyboard button work.

Now open the game scene. I put these buttons here so that when you press a button it's going to go ahead and run something in the script. The buttons script is what on the canvas click keyboard and mouse.

Whenever you click any of the two-button, there should be a full object movement on the screen

Summary

I hope you understood how to perform change controls by pressing a button using C# Script in Unity 3D. For any doubts and help, please feel free to comment.


Similar Articles