- Home /
Persistent prefabs after exit
Hi,
I have a prefab that is copied multiple times in my scene. When I run a script it changes properties like color and other things.
When I change scene and come back they where all duplicate, so I added a singleton to the prefab, but now the problem is that it destroys all objects in de scene except one.
Another thing I noticed is that if I quit unity and come back my objects get a different ID. My question is: 1) How can I make all prefabs-objects persistent if I change scene. 2) How can I make the Ids persistent after exit.
I'm quite new to unity so I would be grateful if somebody could point me in the right direction.
Here is the code attached to the prefab:
int hmWidth; // heightmap width
int hmHeight; // heightmap height
int posXInTerrain; // position of the game object in terrain width (x axis)
int posYInTerrain; // position of the game object in terrain height (z axis)
int size = 1; // the diameter of terrain portion that will raise under the game object
float desiredHeight = -1; // the height we want that portion of terrain to be
//variables for the age
int currentYear = System.DateTime.Now.Year;
[SerializeField]
public int yearBuild {get;set;}
// variables for the MarkovChane
private MarkovChane markovChane;
[SerializeField]
public int currentState {get;set;}
[SerializeField]
public int probability {get;set;}
private GameObject markovScript;
//variables to save the object
private string fileName;
private string filePath;
ManholeData manholeData;
private static bool manholeExists;
//public variables in inspector
[Header("General")]
public int ID;
public Terrain Terrain;
public Text year;
public int infrastrInitialBuild;
[Header("Finance")]
public float valueNew;
public float replacementCosts;
public int replacementDisruption;
public float inspectionCosts;
public int inspectionDisruption;
public int streetDamage;
[Header("Health")]
public Image healthBar;
public Text probabPerc;
public Color[] healtColor = new Color[5];
[Header("Death Effects")]
public GameObject explosionEffect;
public float blastRadius = 5f;
public float explosionForce = 700f;
public GameObject destroyedObject;
public Transform smokeEffect;
private void Awake()
{
ID = gameObject.GetInstanceID();
markovChane = FindObjectOfType<MarkovChane>();
fileName = "/" + ID + "Data.json";
filePath = Application.persistentDataPath + fileName;
if(!manholeExists)
{
manholeExists=true;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
if(manholeData == null)
{
manholeData = new ManholeData();
}
}
void Start()
{
if (!File.Exists(filePath))
{
//calculates a random build-year ans pass it to the MarkovChane
yearBuild = Random.Range(infrastrInitialBuild, currentYear);
year.text = yearBuild.ToString();
markovChane.Age(yearBuild);
//saveGameData
manholeData.savedID = ID;
manholeData.savedState = currentState;
manholeData.savedProb = probability;
manholeData.savedYearBuild = yearBuild;
string json = JsonUtility.ToJson(manholeData);
File.Create(filePath).Dispose();
File.WriteAllText(filePath,json);
// Terrain = Terrain.activeTerrain;
hmWidth = Terrain.terrainData.heightmapWidth;
hmHeight = Terrain.terrainData.heightmapHeight;
}
else
{
string json;
json = File.ReadAllText(filePath);
manholeData = JsonUtility.FromJson<ManholeData>(json);
currentState = manholeData.savedState;
probability = manholeData.savedProb;
yearBuild = manholeData.savedYearBuild;
healthBar.color = healtColor[currentState];
probabPerc.text = probability.ToString() + "%";
year.text = yearBuild.ToString();
}
}
void Update()
{
}
public void Health(int state)
{
if (!File.Exists(filePath))
{
//gets the state back from the MarkovChane and calculates the probability that the asset is actually in given state
currentState = state;
probability = Random.Range(1,100);
if(probability >=75 || probability <=88 && state !=0)
{
currentState = currentState-1;
}
else if(probability >= 88 && state !=5)
{
currentState = currentState+1;
}
healthBar.color = healtColor[currentState];
probabPerc.text = probability.ToString() + "%";
if(currentState == 4)
{
Explosion();
}
}
}
void Explosion()
{
//show effect
Instantiate(explosionEffect, transform.position, transform.rotation);
//Add Force
Collider[] collidersToDestroy = Physics.OverlapSphere(transform.position, blastRadius);
//Replace the GameObject with the destroyed one
Instantiate(destroyedObject, transform.position, transform.rotation);
Destroy(gameObject);
//Shatter the pieces around
Collider[] collidersToMove = Physics.OverlapSphere(transform.position, blastRadius);
foreach (Collider nearbyObject in collidersToMove)
{
Rigidbody rb = nearbyObject.GetComponent<Rigidbody>();
if (rb != null)
{
rb.AddExplosionForce(explosionForce, transform.position, blastRadius);
}
}
// Damage left: Crater and smoke
// get the normalized position of this game object relative to the terrain
Vector3 tempCoord = (transform.position - Terrain.gameObject.transform.position);
Vector3 coord;
coord.x = tempCoord.x / Terrain.terrainData.size.x;
coord.y = tempCoord.y / Terrain.terrainData.size.y;
coord.z = tempCoord.z / Terrain.terrainData.size.z;
// get the position of the terrain heightmap where this game object is
posXInTerrain = (int)(coord.x * hmWidth);
posYInTerrain = (int)(coord.z * hmHeight);
// we set an offset so that all the raising terrain is under this game object
int offset = size / 2;
// get the heights of the terrain under this game object
float[,] heights = Terrain.terrainData.GetHeights(posXInTerrain - offset, posYInTerrain - offset, size, size);
// we set each sample of the terrain in the size to the desired height
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
heights[i, j] = desiredHeight;
// go raising the terrain slowly
desiredHeight += Time.deltaTime;
// set the new height
Terrain.terrainData.SetHeights(posXInTerrain - offset, posYInTerrain - offset, heights);
Instantiate(smokeEffect, transform.position, transform.rotation);
}
[System.Serializable]
public class ManholeData
{
public int savedID;
public int savedState;
public int savedProb;
public int savedYearBuild;
}
Your answer
Follow this Question
Related Questions
[Probably an easy question]Troubles saving my GameObject through scenes 1 Answer
How to get items(my custom class) by a custom id I paired them to? 1 Answer
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Can't activate game object. 3 Answers
Is there a way to dynamically populate game objects via texture maps? 2 Answers