Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning C# by Developing Games with Unity 5.x - Second Edition

You're reading from  Learning C# by Developing Games with Unity 5.x - Second Edition

Product type Book
Published in Mar 2016
Publisher Packt
ISBN-13 9781785287596
Pages 230 pages
Edition 2nd Edition
Languages

Table of Contents (20) Chapters

Learning C# by Developing Games with Unity 5.x Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
1. Discovering Your Hidden Scripting Skills and Getting Your Environment Ready 2. Introducing the Building Blocks for Unity Scripts 3. Getting into the Details of Variables 4. Getting into the Details of Methods 5. Lists, Arrays, and Dictionaries 6. Loops 7. Object, a Container with Variables and Methods 8. Let's Make a Game! – From Idea to Development 9. Starting Your First Game 10. Writing GameManager 11. The Game Level 12. The User Interface 13. Collectables — What Next? Index

Chapter 13. Collectables — What Next?

Great progress so far! You are able to create and control a good-looking and functional UI. Let's move on. In this chapter, we will cover the following topics:

  • Introducting collectables

  • Preparing collectable prefabs

  • The score and high score

  • Persisting data using player prefs

  • What's next? Your path to greatness

Collectables


All objects in a game that the player is able to collect are called collectables. Probably, you are a gamer yourself and this concept should be fairly familiar to you. In our game, we will add collectable coins scattered in the level's pieces for the player to collect. I am not going to talk too much about what collectables are and why it is good to use them as I believe it is pretty obvious. Let's skip all that and make a simple plan:

  • Our collectables—let's call them coins from now on—will be collected on contact with the player game object

  • We will write the Collectable class to manage coin behavior

  • For every coin collected, we will count and increment the number of collected coins on the UI

  • The count of total collected coins will restart with the new game

The coin prefab


To make things a little easier, I have already prepared the visual part of our coin. Download Coin.unitypackage and import it into your project:

Great job! Now we drag the Coin prefab into the Hierarchy view so that we can take a look at it. As mentioned before, I prepared this prefab visually. I have added Sprite Renderer to the game object and linked it with the coin sprite. I have also created a simple spin animation controlled by the Animator. Don't worry about it right now.

Now, you have to pick up from where I finished. Most collectables react with the environment through the physics of the game. We can use the 2D trigger here to react with the Player Game Object Rigidbody2D component. This is the exactly the same way we inserted LeaveTriggers into the game previously.

Select the coin and add the CircleCollider2D component. A green circle will appear around the coin, representing the triggering area. Make sure you tweak the radius value to roughly match the size of the...

High score and persisting data


Pretty much every game has some sort of scoring system. You will now learn how to write simple code that calculates the score based on the distance the Player has traveled since the start of the level. We will then use this score value and store it in Unity PlayerPrefs to make sure that the value is remembered between sessions. PlayerPrefs is a very useful built-in Unity class that allows us to store and access data between Unity sessions.

Let's write the following method in the Player class:

We have finally come to a real-life example of a method that returns something. As you can see, the GetDistance() method returns a float value—the distance between the starting point and the current position of the player game object.

I won't go too much into the detai here. I encourage you to dive into the Unity Scripting Reference and search for Vector2.Distance to understand exactly how it works.

Having the GetDistance() method working, we can now call it from any place...

The Update function and UI values


There is one thing I want to mention here. As you must have noticed, we are updating all UI values in the Update function. As the Update function is called on every frame, we are wasting a lot of computation power there. This isn't the most efficient or correct way of assigning these values for every frame. Ideally, we change the text value only when we need to; for example, when the value actually changes. I decided to show you this way because it's definitely the simplest way. As this book is written for you, a beginner in programming, this way just works.

What next?


Well done! You survived reading your first programming book! We can easily say that you are not suffering from scriptphobia anymore. You have now learned how to write, read, and, most importantly, understand C# code in Unity. The next step for you is very easy—decide what you want to do with your skills! I encourage you to keep working on the game we have started together, or you can start a new one from scratch! The sky is the limit!

Remember, however, that you will gradually gain experience. It would be wise to keep your projects simple and work on them from start to finish. There is nothing better for a game developer than finishing their very own project and publishing it!

Two very good places to show off your games are the Unity forums and the Unity Developers Facebook public group. We would love you to join our community. Yet again, well done! Keep working hard and you will find your very own path to greatness.

The code in this chapter


Let's take a look at the code again to make sure we are on the same page.

The code for Collectable.cs:

using UnityEngine;
using System.Collections;

public class Collectable : MonoBehaviour {
  
  bool isCollected = false;

  void Show() {
    this.GetComponent<SpriteRenderer>().enabled = true;
    this.GetComponent<CircleCollider2D>().enabled = true;
    isCollected = false;
  }

  void Hide() {
    this.GetComponent<SpriteRenderer>().enabled = false;
    this.GetComponent<CircleCollider2D>().enabled = false;
  }


  void Collect() {

    isCollected = true;
    Hide();
    GameManager.instance.CollectedCoin();
  }

  void OnTriggerEnter2D(Collider2D other) {
    
    if (other.tag == "Player") {
      Collect();
    }
  }  
}

The code for playerController.cs:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public static PlayerController instance;

  public float jumpForce = 6f;
  public float...

Summary


In this chapter, you learned about collectables, counting the player's score, and persisting data.

You can definitely call yourself a game developer now. You've learned so much recently. I bet you want to take your skills further. I really hope you enjoyed this book and will leave positive reviews about the book, or even recommend it to someone directly. Thanks!

lock icon The rest of the chapter is locked
You have been reading a chapter from
Learning C# by Developing Games with Unity 5.x - Second Edition
Published in: Mar 2016 Publisher: Packt ISBN-13: 9781785287596
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}