Ambiera ForumDiscussions, Help and Support. |
|
|
|||||
|
I keep reading posts and information about the read content from file function, write content to txt file etc. I guess I don't understand. How would I write a small script, and lets say I wanted manipulate a variable by reading it from the content from external txt file? How would write to file a new value for a variable, and the read it back in again later during the life of the executable? Can someone please help me with some thorough code examples? With some // comments? For example, I fly my ship to planet "A". I want to save the specs/inventory/upgrades of my ship, MyShip. Save MyShip's inventory and ccbSwitch Scene to another scene where my player/pilot(s) are on the planet with their seperate inventory for surface encounters??? |
||||
|
Hi, Basically, what you need to do is to: 1. Serialize your data; 2. Write content to the file; then later 3. Read content from the file; 4. Deserizlize data; In context of your task serialization is converting you data structures, i.e. your variables to the string which then can be written to the file. Deserialization is a reverse process - you read the string and convert it back to the same data structure. In the world of JS you usually use global JSON object for that. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON. It only has 2 funcitons - parse and stringify - which is exactly that's needed. But, as always there is a catch. Coppercube uses some really old JavaScript version, which I believe, is actually the ES1 - a very first version which appeared in 1997. And this global JSON object appeared in only ES5 which came 12 years later. But, it's actually resolvable, since in the magic world of JS there are Polyfills. These are libraries which add new feature supports for the old browsers. For example IE doesn't support most of the modern JS features and there are always polyfills used there for it to be able to render the modern sites. There are even transcompillers like Babel which allow to compile the code written with a newer JS versions to older JS versions. In order to use JSON in ES1 we need a corresponding polyfill. So, overall: 1. At first you data structure. I'm not sure how do you store your items/upgrades information, but I would store it in a regular array as a property of some scens node's behavior. Something like: this.inventory = [ In order to serialize this array we have to add a JSON object polyfill. This implementation is taken from the mozilla site:
2. Not it's possible to serialize this.inventory into string and write into file:
3. You can read the file context and deserialize the content back:
4/ Deserilize and assign back:
That's it:) |
|