Save and Load Systems Richard Gesick.

Slides:



Advertisements
Similar presentations
Program Verification Using the Spec# Programming System ETAPS Tutorial K. Rustan M. Leino, Microsoft Research, Redmond Rosemary Monahan, NUIM Maynooth.
Advertisements

Reading and Writing Text Files Svetlin Nakov Telerik Corporation
Execute Blocks of Code Multiple Times Svetlin Nakov Telerik Corporation
Mobile Development Storing State with XML Rob Miles Department of Computer Science.
Execute Blocks of Code Multiple Times Telerik Software Academy C# Fundamentals – Part 1.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
Using Multiple Forms. Creating a New Form ProjectAdd Windows Form.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Microsoft Visual Basic 2005 CHAPTER 9 Using Arrays and File Handling.
Using Arrays and File Handling
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
C++ Basics Structure of a Program. C++ Source Code Plain text file Typical file extension .CPP Must compile the C++ source code without errors before.
File I/O 11_file_processing.ppt
File I/O Static void Main( ) {... } data. Topics I/O Streams Reading and Writing Text Files Formatting Text Files Handling Stream Errors File Pointers.
Module 3: Working with Components. Overview An Introduction to Key.NET Framework Development Technologies Creating a Simple.NET Framework Component Creating.
Adding a New Option to the Framework. Introduction This is intended as a step by step guide to adding a new action to the menu or toolbar. The order of.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
File I/O What We’ll Cover –Visual Basic Techniques for Text Files –.NET Techniques for Text Files What We’ll Not Cover –Binary File I/O –XML File I/O.
Applications Development
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
CS360 Windows Programming
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
BIM313 – Advanced Programming File Operations 1. Contents Structure of a File Reading/Writing Texts from/to Files File and Directory Operations 2.
6-1 Chapter 6 Working with Arrays in VB.NET. 6-2 Learning Objectives Understand the use of list and table arrays in VB.NET projects and the difference.
Building Your Own Class. We will build a simple instance class for an inventory control application and a main program to test it. We need an Item class.
CSC 298 Streams and files.
File IO.  File Input/Output  StreamWriter  StreamReader  Text Files  Binary Files.
GameDevClub CODE CHEAT SHEET NOTE: ALL OF THE CODE IS CASE-SENSITIVE AND THE SYNTAX IS STRICT SO A LOT OF YOUR ERRORS WILL PROBABLY COME FROM TYPOS If.
Debugging tools in Flash CIS 126. Debugging Flash provides several tools for testing ActionScript in your SWF files. –The Debugger, lets you find errors.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 11 Data Files.
Lecture 2 Review of 1301 and C# Richard Gesick. Common data types int, long, double, float, char, bool, string.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
CONDITIONALS CITS1001. Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ,
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Lecture 18 File I/O Richard Gesick. File Input / Output Consider that a program may want to make its data persistent (or not rely upon the user for input)
Y.-H. Chen International College Ming-Chuan University Fall, 2004
Review 1.
Lecture 2 Richard Gesick
Reading & writing to files
Files.
Using Multiple Forms.
Error Handling Summary of the next few pages: Error Handling Cursors.
Accessing Files in Java
Using Procedures and Exception Handling
Hacking Minecraft on the Raspberry Pi using Python
Files and Streams Lect3 CT1411.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
File Input/Output (I/O)
Processing XML.
Topics Introduction to File Input and Output
null, true, and false are also reserved.
Conditional Statements
Implementing Classes Chapter 3.
More programming with "Processing"
Keeping Score Richard Gesick.
Lecture 16 File I/O Richard Gesick.
Fundaments of Game Design
CIS16 Application Development and Programming using Visual Basic.net
Fundaments of Game Design
Fundaments of Game Design
Welcome back to Software Development!
Topics Introduction to File Input and Output
Lecture 18 File I/O CSE /5/2019.
Presentation transcript:

Save and Load Systems Richard Gesick

Objectives Save data to a flat file Load data from a flat file Customize our flat file Save data to an XML file Load data from an XML file Implement a checkpoint-based system Implement an anywhere/anytime saving system

flat/text files StreamWriter for writing files StreamReader for reading files Same basic commands as in Console’s ReadLine and WriteLine Need using System.IO; and using System.Text; Application.dataPath Application.persistentdataPath

Saving a text file void WriteToFile(string file = "") { if(file != "") //good or even necessary? sFileName = file; if(File.Exists(sDirectory + sFileName)) DeleteFile(sFileName); } using(StreamWriter sw = new StreamWriter(sDirectory + sFileName)) sw.WriteLine(PlayerPrefs.GetInt("PlayerKills").ToString()); sw.WriteLine(PlayerPrefs.GetInt("PlayerDeaths").ToString()); sw.WriteLine(PlayerPrefs.GetInt("PlayerTotalGold").ToString()); … sw.WriteLine(Player.transform.position.x.ToString()); sw.WriteLine(Player.transform.position.y.ToString()); sw.WriteLine(Player.transform.position.z.ToString());

Reading flat/text files void ReadFile(string file = "") { if(file != "") sFileName = file; using(StreamReader sr = new StreamReader(sDirectory + sFileName)) int kills = Convert.ToInt32(sr.ReadLine()); int deaths = Convert.ToInt32(sr.ReadLine()); … float x = Convert.ToSingle(sr.ReadLine()); float y = Convert.ToSingle(sr.ReadLine()); float z = Convert.ToSingle(sr.ReadLine()); Player.transform.position = new Vector3(x, y, z); }

Using streamreader/streamwriter Creates an instance of StreamReader to read from a file. The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader("TestFile.txt")) But does not incorporate exception handling. Still need to include try & catch blocks to handle errors

Handling file not found and other file errors If you have a reset: consider having the catch call the reset method, call the write file method for saving the data and then call the read method again. Be careful because this could be an infinite loop if there are more errors. Other options?

XML save/load system Create a player file <pData> <xPos></xPos> <yPos></yPos> <zPos></zPos> <xRot></xRot> <yRot></yRot> <zRot></zRot> <xScale></xScale> <yScale></yScale> <zScale></zScale> </pData> pData is the root node and the anchor for the data and other nodes The order is not important as long as they are within the root

XML save/load system Create an enemy file <eData> <enemy> <name></name> <xPos></xPos> <yPos></yPos> <zPos></zPos> <xRot></xRot> <yRot></yRot> <zRot></zRot> <xScale></xScale> <yScale></yScale> <zScale></zScale> </enemy> … </eData> eData is the root node and the anchor for the data and other nodes The enemy node holds the rest of the nodes that we save to and load from almost like a class or object. You can consider the enemy to be a class and the child nodes within it as the class's properties. The reason we are doing this is to save multiple enemies to our XML file, and they will each have their own data.

XML files Be sure to add the following using statements using System.Xml; using System.Xml.Serialization; using System.IO; using System.Text;

Within the class Create several new variables XmlDocument xPlayer = new XmlDocument(); XmlDocument xEnemy = new XmlDocument(); public string pFileName = ""; public string eFileName = ""; public GameObject Player; public GameObject[] Enemies; private string[] playerXMLs; private string[] enemyXMLs;

Initial loading Loading the files into the xml docs in start(): playerXMLs = System.IO.File.ReadAllLines (Application.dataPath + "/XML/" + pFileName); xPlayer.LoadXml( GetXMLString( playerXMLs)); enemyXMLs = System.IO.File.ReadAllLines (Application.dataPath + "/XML/" + eFileName); xEnemy.LoadXml( GetXMLString (enemyXMLs)); string GetXMLString (string[] XMLs) { string XMLString = ""; for (int i = 0; i < XMLs.Length; i++) XMLString += XMLs[i]; } return XMLString;

Saving the Player void SavePlayer() { if (Player != null) XmlNode root = xPlayer.FirstChild; foreach (XmlNode node in root.ChildNodes) switch (node.Name) case "xPos": node.InnerText = Player.transform.position.x.ToString(); break; case "yPos": node.InnerText = Player.transform.position.y.ToString(); . . . } } xPlayer.Save(Application.dataPath + "/XML/" + pFileName); }

Saving the enemy void SaveEnemies() { xEnemy.RemoveAll(); XmlNode eRoot = xEnemy.CreateNode(XmlNodeType.Element, "eData", ""); string[] nodes = { "name", "xPos", "yPos", "zPos", "xRot", "yRot", "zRot", "xScale", "yScale", "zScale" }; for (int e = 0; e < Enemies.Length; e++) if (Enemies[e] != null) XmlNode eBase = xEnemy.CreateNode(XmlNodeType.Element, "enemy", ""); for (int n = 0; n < nodes.Length; n++) XmlNode newNode = xEnemy.CreateNode(XmlNodeType.Element, nodes[n], ""); eBase.AppendChild(newNode); }

Saving the enemy 2 foreach (XmlNode node in eBase.ChildNodes) { switch (node.Name) case "name": node.InnerText = Enemies[e].name; break; case "xPos": node.InnerText = Enemies[e].transform.position.x.ToString(); … } eRoot.AppendChild(eBase); xEnemy.AppendChild(eRoot); xEnemy.Save(Application.dataPath + "/XML/" + eFileName);

Loading the player Declare and initialize all the player variables then: if (Player != null) { XmlNode root = xPlayer.FirstChild; foreach (XmlNode node in root.ChildNodes) switch (node.Name) case "xPos": xPos = Convert.ToSingle(node.InnerText); break; … } Player.transform.position = new Vector3(xPos, yPos, zPos); Player.transform.rotation = new Quaternion(xRot, yRot, zRot, 0.00f); Player.transform.localScale = new Vector3(xScale, yScale, zScale);

Loading the enemies Declare and initialize all the enemy variables then: for (int e = 0; e < Enemies.Length; e++) { if (Enemies[e] != null) XmlNode eData = xEnemy.FirstChild; XmlNode enemy = eData.ChildNodes[e]; if (enemy.Name == "enemy")

Loading the enemies 2 { switch (eNode.Name) case "name": foreach (XmlNode eNode in enemy.ChildNodes) { switch (eNode.Name) case "name": name = eNode.InnerText; break; case "xPos": xPos = Convert.ToSingle(eNode.InnerText); . . . } Enemies[e].name = name; Enemies[e].transform.localPosition = new Vector3(xPos, yPos, zPos); Enemies[e].transform.localRotation = new Quaternion(xRot, yRot, zRot, 0.00f); Enemies[e].transform.localScale = new Vector3(xScale, yScale, zScale); } } } }

Save handler - checkpoint Checkpoints are typically areas in the game world on reaching which the game will save the player's data void OnTriggerEnter(Collider other) { if(other.tag == "SavePoint") Camera.main.SendMessage("WriteToFile"); Destroy(other.gameObject); } take note that this function also destroys the trigger object so that the player can't reactivate the checkpoint

Save handler on demand To allow the player to save their data anywhere they want and anytime they want, add an option for them to call it. This can be done by adding to the menu a key or a button, or both, that the player presses. void Update() { if(Input.GetKeyUp(KeyCode.F1)) Camera.main.SendMessage("SaveEnemies"); } if(Input.GetKeyUp(KeyCode.F2)) Camera.main.SendMessage("LoadEnemies");