- Home /
How to save a random seed to a playerpref
I'm trying to save a random seed to a PlayerPref so the game loads the same world each time, after its been created once first. I know this is wrong, but this is what I have so far.
public int GameWidth;
public int GameHeight;
public int SeedNumber;
public int MapCreated = 0;
// Use this for initialization
void Start () {
if(MapCreated != 1)
{
for(int z = 0; z < GameHeight; z++)
{
for(int x = 0 ; x < GameWidth; x++)
{
float rnd = Random.value;
if(rnd <0.25f)
{
Instantiate(TileOne, new Vector3(x,0,z), Quaternion.identity);
}
else if(rnd <0.5f)
{
Instantiate(TileTwo, new Vector3(x,0,z), Quaternion.identity);
}
else
{
Instantiate(TileThree, new Vector3(x,0,z), Quaternion.identity);
}
}
}
PlayerPrefs.GetInt("MapCreated", 1);
SeedNumber = Random.Range(1,1000);
}
if(MapCreated == 1)
{
PlayerPrefs.GetInt("Seed", SeedNumber);
Random.seed = SeedNumber;
}
}
I'm trying to do it like this
Create world. Get worlds seed. Save the worlds seed. Use the saved seed from now on when loading the world.
I think most of my problem comes from the fact that I'm not sure how to use PlayerPrefs correctly. If anyone can show or explain how I'd appreciate it.
Answer by perchik · Jun 05, 2014 at 04:24 PM
Use SetInt to save a value in playerprefs. Think of playerprefs like bank of boxes, where each box has a name. Set*
put something in a box and tells the box what it's name is. Get*
gets whatever is in the box with the name you supplied.
*
String, Int or Float
Okay so... I create the world to make the seed. Then I Set the seed to the Playerpref. Then when I want to return to that world I Get the seed from the playerpref.
Answer by PouletFrit · Jun 05, 2014 at 04:32 PM
You need to check if you have the seed key in PlayerPref, then take decision based on that.
void Start() {
// First let's check if the seed exist in player prefs
if (PlayerPrefs.HasKey("MapRandomSeed"))
{
// If Map Random Seed exist, lets get that value
int seed = PlayerPrefs.GetInt("MapRandomSeed");
Random.seed = seed;
CreateMap();
}
else
{
// Map Random Seed doesn't exist, so we know that the map wasn't created earlier
CreateMap();
}
}
private void CreateMap(int seed) {
// Create the map as u were doing, now that we have the appropriate seed
for (int z = 0; z < GameHeight; z++)
{
for (int x = 0; x < GameWidth; x++)
{
float rnd = Random.value;
if (rnd < 0.25f)
{
Instantiate(TileOne, new Vector3(x,0,z), Quaternion.identity);
}
else if( rnd < 0.5f)
{
Instantiate(TileTwo, new Vector3(x,0,z), Quaternion.identity);
}
else
{
Instantiate(TileThree, new Vector3(x,0,z), Quaternion.identity);
}
}
}
// Once you created your map save the random seed used
PlayerPref.SetInt("MapRandomSeed",Random.seed);
// Don't forgot to save
PlayerPref.Save();
}