- Home /
save funtion c#
hey guys, I am trying to code a save function for my game. where it saves what i pick up and where i am when i hit a certain checkpoint. So for instance, if there was a thin hallway with 2 apples on the ground, that i can pick up, one right in front of me, and one at the end of the hallway, i would want it to save when i pick up the second apple and the end of the hall. i don't want it to save at the point where i pick up the object, i would like it to be when i walk through a collider of an empty game object or possibly a trigger of some sort. i don't think i want it to keep the players position if they exit the game.
thanks for any help you can offer
best.
Answer by foxtrot117 · Mar 24, 2018 at 01:36 AM
Create a script:
CheckPointManager : MonoBehaviour
{
public static Vector3 lastCheckPoint = new Vector3 (0,0,0);
public static int numberOfApples;
public static int numberOfBananas;
}
Create script:
CheckPoint : MonoBehaviour
{
OnTriggerCollision (Collider other)
{
if (other.tag == "Player")
{
CheckPointManager.lastCheckPoint = this.transform.position;
}
}
}
Same logic with with the collectibles. -Hope i helped
so, what if i wanted a it to be saved when the player exits? and then when they come back to the game it asks if they want to continue or restart ?
That is a little more complicated. You have to write the data in a file like a .txt, json or something like that. .txt i believe is the best way to start with as it simpler and help you learn the process. Other formats however are much more commonly used and you should probably change to them when you have learn the basic idea. Check $$anonymous$$SDN documentation about Stream()
, StreamWriter()
and StreamReader()
. These are some classes that will help you write/read to/from .txt files. You can find many tutorials if you search about it. Unity also have a way to save data (or even many ways). The simplest one is using the "player preferences" but this is not a final solution as it only allows you to save a max of some $$anonymous$$B. An other way Unity provides is by using its "Serialization" classes and attributes. Last there is the "scripting" way, which is also Unity specific. I am not so sure about this and might be the same with the "Serialization" thing. Never checked both of them, i prefer the .txt - json way as they are more generic and can be used out from Unity too.
Useful links: https://unity3d.com/learn/tutorials/topics/scripting/persistence-saving-and-loading-data
Generally the are many good tutorials for all the methods mentioned, try searching: "how to save data in Unity" and good things will happen :) -Hope i helped
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Object type System.Boolean cannot be converted to target type: System.Int32 ? 0 Answers
Checkpoint script problem 1 Answer
How to create log by PlayerPrefs? 1 Answer