Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource
Table of Contents

Unity Scripting

If you have just started out in the Game Development industry, you would love to create your first game successfully. If so, then we welcome you to Unity Scripting, where you will learn how to code to transform the real, dynamic world into a virtual one. When understanding What is Unity, it is important to recognise that it is a versatile game development platform that offers the ability to bring digital dreams to life with its diverse features.  

Among the most significant of these is the Unity Scripting system. Unity's Scripting environment allows developers to dictate the rules of their game world, from the characters’ interactions with the environment to the fundamental laws that govern the game universe. venturebeat.com mentioned that "In its Unity Gaming Report 2022, the company said that it drew information from more than 230,000 developers who make and operate over 750,000 games based on Unity.” 

This blog will explore the fundamentals of Unity Scripting and how to control game objects. We will also learn to implement interactive gameplay mechanics and create immersive experiences. 

Table of Contents 

1) What do you understand by Unity Scripting? 

2) How can you Implement Interactive Gameplay Mechanics with Unity Scripting? 

     a) How do you create “Player”? 

     b) How do you create “Player Movement Script”? 

     c) How do you create “Camera Script”? 

     d) How do you create “Enemy Script”? 

     e) How do you create “Prefabs”? 

     f) How do you create “Scene”? 

     g) How do you create “Firing Projectiles”? 

     h) How do you create “More Characters”? 

     i) How do you create “Game Controller”? 

     j) How do you create Script for “Detecting User Input”? 

3) How can you optimise Unity Scripting? 

4) Conclusion 

What do you understand by Unity Scripting? 

Unity Scripting is the process of writing Scripts or pieces of code in the Unity Game Engine to control game behaviour, playing a crucial role in Unity Game Development. It's essentially the "brain" behind all the actions, reactions, and interactions that take place within the game. From how characters move and interact with their environment to how UI elements respond to user actions to complex AI behaviours, Unity Scripting makes it all possible. 

 Unity primarily uses C# (pronounced C Sharp), a powerful, versatile language that's widely used in the game industry. These Scripts are attached to “GameObjects”. These are the fundamental objects in Unity that represent characters, scenery, Cameras, and more. Each Script is executed within Unity's game loop, allowing it to react to Player input, initiate animations, trigger game events, and so on. 

As a game developer, you must be aware that Unity Scripting is the backbone of game development in Unity, enabling developers to bring their creative visions to life. With the help of Unity Scripting, you can make each of your games interesting and one of a kind. Read further into this blog to discover how! 

Don't wait any longer to turn your game development dreams into reality - start your journey with our Game Development Training 

How can you implement interactive Gameplay Mechanics with Unity Scripting? 

Without any further ado, let us look at some ways that Unity Scripting will help you create your first game. These pointers will remain almost constant throughout the number of games that you create in that future. You can tweak them as per your choice. 

Implementing interactive Gameplay Mechanics with Unity Scripting
 

Let’s begin:

a) How do you create “Player”? 

Creating a “Player” in Unity involves creating a game object, attaching a sprite (or model for 3D), and adding a Script to control the “Player's” behaviour. We will focus on the Script aspect in this section. Here's a simple way to create a Player Controller in Unity: 

1) You should have a Player “GameObject” to which the Script can be attached. You can create one by navigating to “GameObject” > Create Empty in Unity's interface. Name it "Player". For simplicity, let's assume that our “Player” will move horizontally based on user input. 

2) Create a new C# Script called "PlayerController". You can do this by navigating to Assets > 

3) Create > C# Script in Unity's interface. Then, attach this Script to your Player GameObject. 

 Here is a basic PlayerController Script that you can use as a reference: 

 

using System.Collections; 

using System.Collections.Generic; 

using UnityEngine; 

  

public class PlayerController : MonoBehaviour 

    public float speed = 10.0f; 

  

    void Update() 

    { 

        float moveHorizontal = Input.GetAxis("Horizontal"); 

  

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, 0.0f); 

  

        transform.position = transform.position + movement * speed * Time.deltaTime; 

    } 


In this Script: 

1) The “speed” variable controls how fast your Player moves.  

2) The “Update()” method runs once per frame, and inside it, we capture the horizontal input from the user.  

3) The “Input.GetAxis”("Horizontal") function returns a value between -1 and 1, depending on whether the left or right key is pressed. This value is then used to create a new Vector3, which represents the direction and magnitude of the desired movement. 

4) The “Player's” current position is updated based on this movement, the speed, and “Time.deltaTime”, which ensures the “Player” moves smoothly regardless of the frame rate. You can attach this Script to your “Player” game object by pressing the play button. This should allow you to control your “Player's” horizontal movement using the arrow keys or 'A' and 'D' keys. 

b) How do you create “Player Movement Script”? 

Creating a Player movement Script in Unity is a fundamental step in any game development process. The following instructions guide you to create a simple Script that allows a Player to move in four directions: up, down, left, and right. 

You can start by creating a new C# Script. You can do this by going to the Project panel, right-clicking in the Assets folder, and then selecting Create > C# Script. Name this Script 'PlayerMovement'. Then, double-click your new 'PlayerMovement' Script to open it in your Script editor.  

Here is a basic example of what this Script might look like: 

 

using System.Collections; 

using System.Collections.Generic; 

using UnityEngine; 

  

public class PlayerMovement : MonoBehaviour 

    public float moveSpeed = 5f; 

    private Rigidbody2D rb; 

    Vector2 movement; 

  

    // Start is called before the first frame update 

    void Start() 

    { 

        rb = GetComponent(); 

    } 

  

    // Update is called once per frame 

    void Update() 

    { 

        // Input 

        movement.x = Input.GetAxisRaw("Horizontal"); 

        movement.y = Input.GetAxisRaw("Vertical"); 

    } 

  

    void FixedUpdate() 

    { 

        // Movement 

        rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime); 

    } 


Here's what this Script does: 

1) The “moveSpeed” variable determines how fast your Player will move. 

2) The “Rigidbody2D” component, denoted as rb, is used to physically move the Player around the 2D environment.  

3) The movement variable is a 2D vector that captures input from the Player. 

4) In the “Start()” function, we initialise the rb variable by getting the “Rigidbody2D” component attached to the Player game object.  

5) In the “Update()”function, we're capturing the input from the Player. The “Input.GetAxisRaw()” function returns -1, 0, or 1, depending on whether the Player is pressing the movement keys (WASD or Arrow keys). 

6) The “FixedUpdate()” function, which is called at a fixed interval, applies the captured input to move the Player's Rigidbody2D. 

7) Attach this Script to your Player game object, and your Player will be able to move in four directions.  

Remember, for this to work, your Player game object needs a “Rigidbody2D” component. You can add this in Unity's Inspector panel with Add Component > Physics 2D > Rigidbody 2D. Also, set its Gravity Scale to 0 to prevent it from falling due to gravity. 

Game Development Training
 

c) How do you create “Camera Script”?   

The Camera in a Unity game is what renders the scenes to be displayed to the Player. By creating a Camera Script, you can control its movement and how it follows the Player, providing a dynamic viewing experience.  

To begin, create a new C# Script in Unity and name it "CameraFollow". Open it in your Script editor and input the following code: 

 

using System.Collections; 

using System.Collections.Generic; 

using UnityEngine; 

  

public class CameraFollow : MonoBehaviour 

    public Transform Player; 

    public Vector3 offset; 

  

    // Update is called once per frame 

    void LateUpdate() 

    { 

        transform.position = Player.position + offset; 

    } 


In this Script:  

1) “Transform Player” is a public variable that refers to our Player's Transform. 

2) “Vector3 offset” is a public Vector3 variable that allows us to offset the position of the Camera.  

3) “LateUpdate()” is a built-in Unity function that is called after all “Update()” functions have been called. This is perfect for Camera following Scripts because we know that the Player's Movement for that frame has finished. Now, we can move the camera accordingly. 

4) Within “LateUpdate()”, we set the Camera's position to the Player's position plus the offset.  

To use this Script: 

1) Drag and drop this Script onto your Main Camera in the Unity Editor. 

2) In the Inspector panel, drag and drop your Player from the hierarchy to the 'Player' field under the Camera Follow Script component. 

3) Adjust the 'Offset' fields to determine where the Camera will follow the Player from. 

4) Now, when you play your game, your Camera will follow your Player around the map, maintaining the offset you've specified. 

Level up your Unity skills with C# Programming For Unity Game Development Training . 

d) How do you create “Enemy Script”?   

In Unity, creating a Script for enemy behaviour is an essential part of any game. In the simplest form, you might want an enemy to patrol an area and chase the Player if they come close. Create a new C# Script named "EnemyController" and open it in your Script editor.  

The Script may look something like this: 

 

using System.Collections; 

using System.Collections.Generic; 

using UnityEngine; 

  

public class EnemyController : MonoBehaviour 

    public float speed = 3.0f; 

    public float chaseDistance = 5.0f; 

    private Transform Player; 

  

    // Start is called before the first frame update 

    void Start() 

    { 

        Player = GameObject.FindGameObjectWithTag("Player").transform; 

    } 

  

    // Update is called once per frame 

    void Update() 

    { 

        if (Vector3.Distance(Player.position, transform.position) < chaseDistance) 

        { 

            Vector3 direction = Player.position - transform.position; 

            direction.Normalize(); 

            transform.position += direction * speed * Time.deltaTime; 

        } 

    } 

}


In this Script: 

1) “speed" controls how fast your enemy moves. 

2) “chaseDistance” is the distance within which the enemy starts chasing the Player. 

3) “Player" is a reference to the Player's Transform. 

4) In the “Start()” function, we get a reference to the Player's Transform by finding a GameObject with the tag "Player". You should make sure your Player GameObject has this tag. 

5) In the “Update()” function, we check the distance between the Player and the enemy. If it's less than “chaseDistance”, we calculate a direction vector from the Enemy to the Player, normalise it (to get a unit vector), and then move the enemy in that direction. 

Attach this Script to your enemy GameObject, and it will chase the Player when the Player comes within the specified “chaseDistance”. You can adjust speed and “chaseDistance” in the Inspector panel in Unity to customise your enemy's behaviour. To make sure everything works as expected, remember to Download Unity and set your Player “GameObject's” tag to "Player" for the script to function properly.

e) How do you create “Prefabs”?  

Prefabs in Unity allow you to create, configure, and store a GameObject complete with all its components, property values, and child GameObjects as a reusable Asset. You can then use this Prefab asset to create instances in various scenes. 

Creating a Prefab doesn't require Scripting but rather is a process done in the Unity Editor. Here's a step-by-step guide: 

1) Create a GameObject in your scene. Configure it by adding the necessary components, setting their properties, and adding any child GameObjects. For instance, you could create an "Enemy" GameObject, attach a Sprite Renderer and an "EnemyController" Script, and customise the values. 

2) Once your GameObject is set up, simply drag it from the Hierarchy window into the Project window. This creates a new Prefab asset in your Assets folder. 

3) To use this Prefab, you can drag and drop it from the Project window into the Hierarchy or Scene view. 

To modify a Prefab: 

1) Click on the Prefab in the Project window. This opens the Prefab Editor. 

2) Make the changes you want in the Inspector. 

3) Click "Apply" to save these changes to the P0refab. All instances of this Prefab in your scenes will be updated with the changes. 

4) You can also create variants of a Prefab, which are like "child" Prefabs that inherit and override properties from their "parent" Prefab. 

 As for Scripting with Prefabs, you might want to instantiate (create) Prefab instances during runtime, which can be done using the Instantiate function. Here's a simple example Script: 

 

using System.Collections; 

using System.Collections.Generic; 

using UnityEngine; 

  

public class SpawnEnemies : MonoBehaviour 

    public GameObject enemyPrefab; 

    public int enemyCount = 5; 

  

    // Start is called before the first frame update 

    void Start() 

    { 

        for (int i = 0; i < enemyCount; i++) 

        { 

            Instantiate(enemyPrefab, new Vector3(i * 2.0F, 0, 0), Quaternion.identity); 

        } 

    } 

}


In this Script, “enemyPrefab” should be set to the Prefab you want to instantiate, and “enemyCount” is the number of Prefab instances you want to create. The Instantiate function creates a new instance of “enemyPrefab” at the specified position and rotation. This Script would create a line of enemies along the x-axis at the start of the game. 

Jumpstart your career in game design with Game Design And Development With Unity Training 

f) How do you create “Scene”?  

A scene in Unity is like a unique level of the game. It contains all the elements like objects, lights, Camera, and Scripts. The Unity Engine uses these to produce a real-time interactive experience. You can create, open, and save scenes in the Unity Editor. 

Creating a scene doesn't require a Script, but it's done through the Unity Editor: 

1) Open Unity Editor and click on File in the menu. 

2) Select New Scene. You now have a blank scene ready to be filled with game objects, lights, and Scripts. 

However, if you want to switch between scenes in your game (e.g., from a main menu to a game level), you can use the “SceneManager “class from the “UnityEngine.SceneManagement” namespace. 

Here's an example of a Script that loads a scene when you press a key: 

 

using System.Collections; 

using System.Collections.Generic; 

using UnityEngine; 

using UnityEngine.SceneManagement;  // Required to manage scenes 

  

public class SceneSwitcher : MonoBehaviour 

    // Update is called once per frame 

    void Update() 

    { 

        if (Input.GetKeyDown(KeyCode.Space)) 

        { 

            SceneManager.LoadScene("MyGameLevel");  // Replace "MyGameLevel" with your scene name 

        } 

    } 

}


In this Script: 

“SceneManager.LoadScene”("MyGameLevel") loads a scene named "MyGameLevel". You need to replace "MyGameLevel" with the name of your scene. This Script will load a specified scene when you press the Space key. Note that for this to work, you need to add the scene you want to load to the list of scenes in the Build Settings (File > Build Settings). 

g) How do you create “Firing Projectiles”?  

Firing Projectiles is a common game mechanic in many game genres. Here is a basic example of how you can achieve this in Unity. For this example, we will assume that the projectile is a simple sphere GameObject. 

First, you have to create a new C# Script called "FireProjectile" and open it in your Script editor. The code might look something like this in Unity Script: 

 

using System.Collections; 

using System.Collections.Generic; 

using UnityEngine; 

  

public class FireProjectile : MonoBehaviour 

    public GameObject projectilePrefab; 

    public float projectileSpeed = 20.0f; 

  

    // Update is called once per frame 

    void Update() 

    { 

        if (Input.GetKeyDown(KeyCode.Space)) 

        { 

            GameObject projectile = Instantiate(projectilePrefab, transform.position, Quaternion.identity) as GameObject; 

            Rigidbody rb = projectile.GetComponent(); 

            rb.velocity = transform.forward * projectileSpeed; 

        } 

    } 

 

In this Script: 

1) “projectilePrefab” is a reference to the Prefab of your projectile. 

2) “projectileSpeed” is the speed at which your projectile will be fired. 

3) In the “Update()” function, we check for the Space key press. When pressed, we instantiate (create) a new instance of “projectilePrefab” at the current position of the “GameObject” to which this Script is attached (presumably, your Player or a weapon).  

Then, we get the “Rigidbody” component of the new projectile (which should be added to your projectile Prefab in advance) and set its velocity to “projectileSpeed” in the forward direction of the GameObject to which this Script is attached. 

To use this Script: 

1) Attach the Script to the “GameObject” from which you want to fire projectiles (e.g., your Player or a weapon). 

2) Drag and drop your projectile Prefab to the Projectile Prefab field in the Inspector panel in Unity. 

3) Make sure your projectile Prefab has a “Rigidbody” component. 

4) Now, when you press the Space key, a projectile should be fired from your GameObject. 

h) How do you create “More Characters”?  

Creating More Characters in Unity involves the creation of new GameObjects and the application of relevant Scripts, sprites, and Prefabs as per the requirements of your game. Let's see how to create a simple AI-controlled character in Unity. You can also use this as a reference to create more “Enemies” in your game. 

1) First, create a new GameObject in Unity and name it "AICharacter".  

2) Add a sprite to this character for visual representation. 

3) Now, create a new C# Script called "AICharacterController" and open it in your Script editor.  

The Script could look something like this:
 

using System.Collections; 

using System.Collections.Generic; 

using UnityEngine; 

public class AICharacterController : MonoBehaviour 

    public float speed = 2.0f; 

    private Transform target; 

  

    // Start is called before the first frame update 

    void Start() 

    { 

        // Setting the target to be the Player 

        target = GameObject.FindGameObjectWithTag("Player").transform; 

    } 

    // Update is called once per frame 

    void Update() 

    { 

        // Move our AI character towards the target (Player) at the defined speed 

        transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime); 

    } 


In this Script: 

1) “speed” is the speed at which the AI character moves. 

2) “target” is a reference to the target GameObject, presumably the Player. 

3) In the “Start()” function, we find the Player “GameObject” by searching for a “GameObject” with the tag "Player". 

4) In the “Update()” function, we move the AI character towards the Player using Vector2.MoveTowards(). 

To use this Script: 

1) Attach it to your "AICharacter" GameObject. 

2) Make sure the Player GameObject has the "Player" tag. 

3) Set the desired speed in the Inspector panel in Unity. 

By repeating this process and modifying the parameters or AI behaviour Scripts, you can create as many characters as you need. 

Master the art of building engaging HTML5 apps and games with HTML 5 Apps And Game Training . 

i) How do you create “Game Controller”?  

In Unity, a Game Controller Script is a central Script that controls aspects of the game, such as keeping track of the score, managing game states, and transitioning between scenes. Here's a basic example of how you can create a Game Controller Script. 

 

using System.Collections; 

using System.Collections.Generic; 

using UnityEngine; 

using UnityEngine.SceneManagement; 

public class GameController : MonoBehaviour 

    public static GameController instance;  // Singleton instance 

    public int score = 0;

    // Start is called before the first frame update 

    void Start() 

    { 

        // If an instance already exists, destroy this one 

        if (instance != null && instance != this) 

        { 

            Destroy(gameObject); 

        } 

        else 

        { 

            // This is the first instance. Make it the Singleton. 

            instance = this; 

            DontDestroyOnLoad(gameObject);  // Persist across scenes 

        } 

    }

    public void AddScore(int points) 

    { 

        score += points; 

        Debug.Log("Score: " + score); 

    } 

    public void GameOver() 

    { 

        Debug.Log("Game Over"); 

        SceneManager.LoadScene("GameOver");  // Assume you have a GameOver scene 

    } 

}


In this Script:  

1) “instance” is a static reference to the current instance of the “GameController” class. This is a common pattern known as a Singleton, used to ensure that there is only ever one instance of this class. 

2) “score” is an integer variable to keep track of the Player's score. 

3) The “Start()” function sets up the Singleton pattern. If an instance of “GameController” already exists, it destroys the current instance. If this is the first instance, it sets an instance to this and makes sure this GameObject persists across scene changes with “DontDestroyOnLoad()”. 

4) The “AddScore()” function is public and can be called from other Scripts to add points to the score. It prints the current score to the console. The “GameOver()” function is also public and can be called to trigger a game over. It changes the current scene to a hypothetical "GameOver" scene. 

Attach this Script to an empty GameObject in your first scene to create a Game Controller. Other Scripts can interact with it by calling “GameController.instance.AddScore(points)” or “GameController.instance.GameOver()”. 

j) How do you create Script for “Detecting User Input”? 

Detecting user input in Unity is crucial for creating interactive experiences. Unity provides a simple and straightforward way to detect various types of user input, including keyboard, mouse, and touch inputs. 

Here's an example of a Unity Script that detects keyboard and mouse inputs: 

 

using System.Collections; 

using System.Collections.Generic; 

using UnityEngine; 

  

public class DetectInput : MonoBehaviour 

    // Update is called once per frame 

    void Update() 

    { 

        // Detect key press 

        if (Input.GetKeyDown(KeyCode.Space)) 

        { 

            Debug.Log("Space key was pressed"); 

        } 

        // Detect mouse click 

        if (Input.GetMouseButtonDown(0))  // 0 for left button, 1 for right button 

        { 

            Debug.Log("Left mouse button was clicked"); 

        } 

    } 

 

In this Script: 

1) “Update()” function is called once per frame. This is where we check for user inputs. 

2) “Input.GetKeyDown(KeyCode.Space)” checks if the space bar key was pressed during the current frame. 

3) “Input.GetMouseButtonDown(0)” checks if the left mouse button was clicked during the current frame. 

To use this Script, just attach it to any GameObject in your scene. Now, whenever you press the space bar or click the left mouse button, you'll see a message in the console. Remember to replace the debug messages with your own game logic.  

For example, you might want to make a character jump when the space bar is pressed or interact with an object when the mouse button is clicked. You can do this by using Unity Scripting. 

Dive into Python Game Development with our Python Game Development Training With Pygame . 

How can you optimise Unity Scripting? 

Optimising your Scripts in Unity can significantly improve your game's performance and provide a smoother gaming experience. Here are some effective strategies to optimise your Unity Scripts: 

Optimising Unity Scripting
 

1) Avoid frequent calls to expensive functions: Certain Unity API calls like “GetComponent()”, “Find()”, or “Physics.Raycast()” can be expensive. Try to minimise their use or cache the results if possible. 

2) Use coroutines for non-immediate actions: If you have a function that doesn't need to be completed immediately, consider using a Coroutine. This allows the function to be spread out over several frames, reducing the CPU load on a single frame. 

3) Leverage object pooling: Instantiating and destroying objects frequently can cause significant overhead. Instead, use an object pooling system where you "recycle" objects that are no longer needed. 

4) Minimise usage of the update function: The Update function runs every frame, so any code within it can impact performance. Try to keep it as lightweight as possible and move non-essential operations elsewhere. 

5) Use efficient data structures: Depending on the use case, different data structures can be more efficient. For instance, Lists are better for dynamically-sized collections, but Arrays are faster for fixed-size collections. 

6) Be mindful of memory allocation: Frequent memory allocation (e.g., creating new variables in a frequently-called function) can lead to performance issues due to increased garbage collection. 

Unlock the power of gamification in business with Gamification Training 

Conclusion 

Unity Scripting is a powerful tool in Game Development that allows developers to control and enhance the gaming experience. Optimising these Scripts is crucial to ensure smooth performance and responsiveness. This provides a more immersive and enjoyable experience for Players. 

Frequently Asked Questions

What are the Other Resources and Offers Provided by The Knowledge Academy?

faq-arrow

The Knowledge Academy takes global learning to new heights, offering over 3,000 online courses across 490+ locations in 190+ countries. This expansive reach ensures accessibility and convenience for learners worldwide.   

Alongside our diverse Online Course Catalogue, encompassing 19 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.

Upcoming Programming & DevOps Resources Batches & Dates

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross
Unlock up to 40% off today!

Get Your Discount Codes Now and Enjoy Great Savings

WHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.