Unity3D game development: quickly creating a popular level system, unity3d Game Development

Source: Internet
Author: User

Unity3D game development: quickly creating a popular level system, unity3d Game Development

Dear friends, welcome to my blog. I am Qin Yuanpei and my blog address is blog.csdn.net/qinyuanpei.
Today I want to share with you the more popular checkpoints on mobile platforms, the level system is usually used for stand-alone mobile games, such as Angry Birds and defending radish, to organize the game content, players can obtain scores through the unlocked level (the first level is unlocked by default) to unlock new levels, or unlock new levels through paid purchases. Well, in today's article, the blogger will guide everyone to quickly implement a scalable level system. This instance is inspired by the blogger's recent work experience, we hope to help you learn about Unity3D games.

Principle

Configure an Xml file locally to define information about the current game card. parse the file and bind it with the UI to implement a complete level system.

1. Define a level

First, we will define the basic structure of a level:

Public class Level {// <summary> /// Level ID /// </summary> public string ID; /// <summary> /// level Name /// </summary> public string Name; /// <summary> /// whether the level is unlocked /// </summary> public bool UnLock = false ;}

Here, we assume that the name of the level is the same as the scene name of the level in Unity3D. The most important attribute is UnLock. This value is a Boolean variable, indicating whether the level is unlocked, because only unlocked scenarios are accessible in the game.

2. Define the level Configuration File

The following configuration file can be defined from the basic Level of the Level. Xml is used as the storage form of the configuration file:

<?xml version="1.0" encoding="utf-8"?><levels>  <level id="0" name="level0" unlock="1" />  <level id="1" name="level1" unlock="0" />  <level id="2" name="level2" unlock="0" />  <level id="3" name="level3" unlock="0" />  <level id="4" name="level4" unlock="0" />  <level id="5" name="level5" unlock="0" />  <level id="6" name="level6" unlock="0" />  <level id="7" name="level7" unlock="0" />  <level id="8" name="level8" unlock="0" />  <level id="9" name="level9" unlock="0" /></levels>

Similar to the level structure definition, here 0 and 1 are used to indicate the unlock status of the level. 0 indicates that the level is not unlocked, and 1 indicates that the level is unlocked. You can note that the first level is unlocked by default, this is consistent with our intuitive experience when playing games like angry birds. Well, after completing the structural definition of the level and the definition of the configuration file, we will start to think about how to implement a level system, because this does not involve the specific logic in the Unity3D scenario, therefore, our main task in the Level System is to maintain the jump relationship between the main interface scenario and each game scenario. we can note that two things need to be done here, that is, the first step is to load the levels in the configuration file to the main interface in a certain form, and tell the players which levels are unlocked and which ones are not unlocked, when a player clicks a different level, he or she can get a different response. The unlocked level can access and enter the game stage, for ununlocked checkpoints, you need to get more scores or pay for them to unlock the checkpoints. Second, you need to edit the checkpoints, after a player scores or pays a certain fee, the player can unlock the level and enter the game stage. In combination, we need to read and write the configuration file of the level, because we noticed that whether a level is unlocked depends only on the unlock attribute, after understanding this, We will compile a class for maintaining the level.

3. Compile a class to maintain the level

The code is provided directly here, because strictly speaking, this code is not the focus of our attention at the moment, which may make it difficult for everyone to adapt, because the article is clearly teaching us to implement a level system, but at the moment the blogger said this part is not important. Please be careful, because there are more profound things than the code here.

Using UnityEngine; using System. collections; using System. collections. generic; using System. xml; public static class LevelSystem {// <summary> // load The Xml file /// </summary> /// <returns> The levels. </returns> public static List <Level> LoadLevels () {// create an Xml Object XmlDocument xmlDoc = new XmlDocument (); // If a configuration file exists locally, read the configuration file. // otherwise, create a copy of the configuration file locally. // to be cross-platform and readable and writable, use Application. persistentDataPath string filePath = Appl Ication. persistentDataPath + "/levels. xml"; if (! IOUntility. isFileExists (filePath) {xmlDoc. loadXml (TextAsset) Resources. load ("levels ")). text); IOUntility. createFile (filePath, xmlDoc. innerXml);} else {xmlDoc. load (filePath);} XmlElement root = xmlDoc. documentElement; XmlNodeList levelsNode = root. selectNodes ("/levels/level"); // initialize the Level List <Level> levels = new List <level> (); foreach (XmlElement xe in levelsNode) {Level l = new Level (); l. ID = xe. getAttribute ("id"); l. name = xe. getAttribute ("name"); // use the unlock attribute to identify whether the current level is unlocked if (xe. getAttribute ("unlock") = "1") {l. unLock = true;} else {l. unLock = false;} levels. add (l);} return levels ;} /// <summary> /// set the status of a certain level /// </summary> /// <param name = "name"> level name </param>/ // <param name = "locked"> unlock </param> public static void SetLevels (string name, bool unlock) {// create an Xml Object XmlDocument xmlDoc = new XmlDocument (); string filePath = Application. persistentDataPath + "/levels. xml "; xmlDoc. load (filePath); XmlElement root = xmlDoc. documentElement; XmlNodeList levelsNode = root. selectNodes ("/levels/level"); foreach (XmlElement xe in levelsNode) {// locate the level if (xe. getAttribute ("name") = name) {// re-assign if (unlock) {xe to the level based on unlock. setAttribute ("unlock", "1");} else {xe. setAttribute ("unlock", "0") ;}}// Save the xmlDoc file. save (filePath );}}

Here we will first set the level configuration file levels. xml is placed in the Resources directory, because we can use Resources. load () is used to Load local resources. This method has a unique advantage for Unity3D:
* It uses relative paths relative to the Resources directory. Therefore, you do not need to consider relative paths or absolute paths.
* It uses a name to find a local resource, so you do not need to consider the extension and file format issues when using it.
* It can be any type supported by Unity3D, from textures to prefabricated objects to text files. It can be perfectly integrated with the Unity3D API.

After talking about so many of its advantages, we naturally need to talk about its shortcomings. What are its shortcomings? That is, the write operation is not supported. Of course, Unity3D cannot be blamed, because when Unity3D exports the game, it will compress the content in the Rsources directory and then export it, of course, we cannot support write operations in a compressed file. Therefore, we should summarize the common methods for reading and writing resources in Unity3D, what are the common resource read/write solutions in Unity3D?

1. Resources. Load: Read-Only. This method can be used when our Resources do not need to be updated and there is no capacity requirement for local storage.
2. AssetBundle: Read-Only. This method can be used when resources need to be updated and local storage capacity is required.
3. WWW: Read-Only. WWW supports http and file protocols. Therefore, you can use WWW to load a network or local resource.
4. PlayerPrefs: A simple key-value storage structure provided by Unity3D. It can be used to read and write three simple data types: float, int, and string, is a loose Data Storage Solution
5. serialization and deserialization: readable and writable. You can use Protobuf, serialized as Xml, binary, or JSON to read and write resources.
6. Database: readable and writable. You can use databases such as MySQL or SQLite to store data and read and write resources.

Now, after learning about the common Unity3D resource read/write solutions, let's discuss the Path Problem in Unity3D:
1. Application. dataPath: This path is a commonly used path. But do we really know this path? I think there is a big question mark here. Why? Because this path is different on different platforms, you can see from the official API documentation that this value depends on the running platform:
* Unity Editor: <path of the project folder>/Assets
* Mac: <path to the player Application>/Contents
* IOS: <path to the player Application>/

4. Compile the portal File
Using UnityEngine; using System. collections; using System. collections. generic; using UnityEngine. UI; using System. xml. serialization; public class Main: MonoBehaviour {// Level List private List <Level> m_levels; void Start () {// obtain Level m_levels = LevelSystem. loadLevels (); // dynamically generate Level foreach (Level l in m_levels) {GameObject prefab = (GameObject) Instantiate (Resources. load ("Level") as GameObject); // data binding DataBind (prefab, l); // you can specify the parent object prefab. transform. setParent (GameObject. find ("UIRoot/Background/LevelPanel "). transform); prefab. transform. localPosition = new Vector3 (0, 0); prefab. transform. localScale = new Vector3 (, 1); // pass the level information to the level prefab. getComponent <LevelEvent> (). level = l; prefab. name = "Level";} // manually unlock the second Level // in the actual game, players must meet certain conditions to unlock the Level. // This is only used as a demonstration of LevelSystem. setLevels ("level1", true);} // <summary> // data binding // </summary> void DataBind (GameObject go, Level level) {// bind the level name go to the level. transform. find ("LevelName "). getComponent <Text> (). text = level. name; // bind the level image Texture2D tex2D to the level. if (level. unLock) {tex2D = Resources. load ("nolocked") as Texture2D;} else {tex2D = Resources. load ("locked") as Texture2D;} Sprite sprite = Sprite. create (tex2D, new Rect (0, 0, tex2D. width, tex2D. height), new Vector2 (0.5F, 0.5F); go. transform. getComponent <Image> (). sprite = sprite ;}}

In this script, we first load the level information, and then bind the level information to the interface element to implement a simple level selection interface, and artificially unlock the second level. Well, if this is a configuration level configuration file for a formal game, I believe everyone knows how to play the unlocked level for free. Haha! Of course, I don't recommend that you do this because, as a programmer, when you are fully engaged in a project, you will understand how much effort you need to invest to complete a software or game, therefore, we should try not to crack or pirate these things. After all, as a developer, maybe his starting point is to develop a product that everyone will like, but the more practical problem is that developers need to live the same way, so please treat them well. Now let's get down to the point. The UI here is implemented based on UGUI. Don't ask why I don't need NGUI, because I just like UGUI! We know that we need to bind a response event to the UI element of each level, so we need to compile a LevelEvent script for it:

Using UnityEngine; using System. collections; using UnityEngine. UI; using UnityEngine. eventSystems; public class LevelEvent: MonoBehaviour {// public Level level of the current level; public void OnClick () {if (Level. unLock) {// assume that the name of the level is the name of the corresponding scenario. // Application. loadLevel (level. name); Debug. log ("the currently selected level is:" + level. name);} else {Debug. log ("Sorry! The current level has not been unlocked! ");}}}

I remember at the beginning of this article, the blogger mentioned the assumption that the name of the level is consistent with the name of the corresponding game. I believe everyone knows why! In order to let the UI elements of each level know which level they correspond to, we set a level variable. The value of this variable has been initialized when the level is loaded, so here we can know the specific information of each level to complete the event response. Well, today's content is like this. Let's take a look at the final effect!

It can be noted that after the second game is opened, the second level has been unlocked, indicating that the two goals we designed at the beginning have been reached, so the content is like this, if you have any good ideas or suggestions, please leave a message after the article. Thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.