Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Irenemeyer · Apr 05, 2019 at 07:46 PM · gameobjectexitpersistence

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;

 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

149 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges