• 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 DuB86 · Jan 07, 2018 at 01:33 PM · playerinstancesave datainstantiation

Player Save Question

Hi community,

so I got a locker, if I interact with it, playerNormal is destroyed and playerSpaceSuit is instantiated and vice versa. I made a save script for health stat, but the health always aplies to either playerNormal or playerSpaceSuit. They never share the same stat. Please take a look at my scripts

        //This is the Global Instance that saves the health float
         public float health = 3;
         public static Tutorial Instance;
         void Awake()
         {
             if (Instance == null)
             {
                 DontDestroyOnLoad(gameObject);
                 Instance = this;
             }
             else if (Instance != this)
             {
                 Destroy(gameObject);
             }
         }
     
     // This is the relevant code snippets from the playerHealth Script
     // Both playerNormal and playerSpaceSuits have an own playerHealth 
     // Script that are pretty similiar but not quite, both scripts have same code
     // snippets
     
         void Start ()
         {
             health = Tutorial.Instance.health;
             healthSlider.value = Tutorial.Instance.health;
         }
     
         public void SavePlayer()
         {
             Tutorial.Instance.health = health;
         }
     
         public void OnDestroy()
         {
             SavePlayer();
         }

So if playerSpaceSuit takes damage and interacts with the locker, playerNormal doesn't have the health from playerSpaceSuit. If I interact with the locker again and playerSpaceSuit is instantiated, now he has the saved health stat

any Idea?

EDIT: Added Health Scripts:

Let me show you the exact scripts

 // That is the playerNormal Health Script
 
     using System.Collections;
     using System.Collections.Generic;
     using UnityEngine.UI;
     using UnityEngine;
     using UnityEngine.SceneManagement;
     
     public class PlayerHealth : MonoBehaviour {
     
         //public float startHealth = 3;
         public float health;
         public float maxHealth = 3;
     
         private PlayerScript playerScript;
         private bool isDead = false;
         private bool isDamageable = true;
     
         public GameObject player;
         public Transform playerPosition;
         public GameObject playerRagdollRight;
         public GameObject playerRagdollLeft;
         public Slider healthSlider;
         public GameObject player1Canvas;
         public int level = 0;
         /*public GameObject sliderStamina;
         public Slider healthSlider;
         public Image noAttack;
         public Image noStamina;
         public Image taunt;*/
         //public GameObject player1;
     
         void Start ()
         { 
             health = GlobalControl.health;
             healthSlider.value = GlobalControl.health;
             playerScript = GetComponent<PlayerScript>();
         }
     
         public void ApplyDamage(float damage)
         {
             if (isDamageable)
             {
                 health -= damage;
     
                 health = Mathf.Max(0, health);
     
                 healthSlider.value -= damage;
     
                 if (!isDead)
                 {
                     if (health == 0)
                     {
                         isDead = true;
                         Dying();
                     }
                 }
     
                 isDamageable = false;
                 Invoke("ResetIsDamageable", 2);
                 //noAttack.enabled = true;
             }
         }
     
         public void AddHealth(float extraHealth)
         {
             health += extraHealth;
     
             health = Mathf.Min(health, maxHealth);
     
             healthSlider.value += extraHealth;
         }
     
         public void ResetIsDamageable()
         {
             isDamageable = true;
             //noAttack.enabled = false;
         }
     
         public void Dying()
         {
             player.SetActive(false);
             player1Canvas.gameObject.SetActive(false);
             /*sliderStamina.SetActive(false);
             healthSlider.gameObject.SetActive(false);
             noAttack.gameObject.SetActive(false);
             noStamina.gameObject.SetActive(false);
             taunt.gameObject.SetActive(false);*/
             if (playerScript.lookingRight == true)
             {
                 Instantiate(playerRagdollRight, playerPosition.position, Quaternion.identity);
             }
             else if (playerScript.lookingRight == false)
             {
                 Instantiate(playerRagdollLeft, playerPosition.position, Quaternion.identity);
             }
             playerScript.enabled = false;
             Invoke("RestartLevel", 3);
     
         }
     
         public void StartGame()
         {
             SceneManager.LoadScene(0);
         }
     
         public void OnDestroy()
         {
             SavePlayer();
         }
     
         public void SavePlayer()
         {
             GlobalControl.health = health;
         }
     
         public void RestartLevel()
         {
             //yield return new WaitForSeconds(4); if IEnumerator
             //health = startHealth;
             //isDead = false;
             //playerScript.enabled = true;
             SceneManager.LoadScene(level);
             //Instantiate(player1, playerPosition.position, Quaternion.identity);
         }
     }
 
 //that is the playerSpaceSuit HealthScript
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine.UI;
 using UnityEngine;
 using UnityEngine.SceneManagement;
 
 public class PlayerHealthSuit : MonoBehaviour
 {
     //public float startHealth = 3;
     public float health;
     public float maxHealth = 3;
     public float oxygen = 100;
     public float oxygenLoss = 1f;
 
     private PlayerScriptSuit playerScriptSuit;
     private bool isDead = false;
     private bool isDamageable = true;
 
     public GameObject player;
     public Transform playerPosition;
     public GameObject playerRagdollRight;
     public GameObject playerRagdollLeft;
     public Slider healthSlider;
     public Slider oxygenSlider;
     public GameObject player1Canvas;
     public int level = 0;
     /*public GameObject sliderStamina;
     public Slider healthSlider;
     public Image noAttack;
     public Image noStamina;
     public Image taunt;*/
     //public GameObject player1;
 
     void Start()
     {
         health = GlobalControl.health;
         healthSlider.value = GlobalControl.health;
         playerScriptSuit = GetComponent<PlayerScriptSuit>();
     }
 
     void Update()
     {
         oxygen -= oxygenLoss * Time.deltaTime;
         oxygenSlider.value = oxygen;
         if (oxygen == 0 || oxygen <= 0)
         {
             isDead = true;
             Dying();
         }
     }
 
     public void ApplyDamage(float damage)
     {
         if (isDamageable)
         {
             health -= damage;
 
             health = Mathf.Max(0, health);
 
             healthSlider.value -= damage;
 
             if (!isDead)
             {
                 if (health == 0)
                 {
                     isDead = true;
                     Dying();
                 }
             }
 
             isDamageable = false;
             Invoke("ResetIsDamageable", 2);
             //noAttack.enabled = true;
         }
     }
 
     public void AddHealth(float extraHealth)
     {
         health += extraHealth;
 
         health = Mathf.Min(health, maxHealth);
 
         healthSlider.value += extraHealth;
     }
 
     public void ResetIsDamageable()
     {
         isDamageable = true;
         //noAttack.enabled = false;
     }
 
     public void Dying()
     {
         player.SetActive(false);
         player1Canvas.gameObject.SetActive(false);
         /*sliderStamina.SetActive(false);
         healthSlider.gameObject.SetActive(false);
         noAttack.gameObject.SetActive(false);
         noStamina.gameObject.SetActive(false);
         taunt.gameObject.SetActive(false);*/
         if (playerScriptSuit.lookingRight == true)
         {
             Instantiate(playerRagdollRight, playerPosition.position, Quaternion.identity);
         }
         else if (playerScriptSuit.lookingRight == false)
         {
             Instantiate(playerRagdollLeft, playerPosition.position, Quaternion.identity);
         }
         playerScriptSuit.enabled = false;
         Invoke("RestartLevel", 3);
 
     }
 
     public void StartGame()
     {
         SceneManager.LoadScene(0);
     }
 
     public void OnDestroy()
     {
         SavePlayer();
     }
 
     public void SavePlayer()
     {
         GlobalControl.health = health;
     }
 
     public void RestartLevel()
     {
         //health = startHealth;
         //isDead = false;
         //playerScript.enabled = true;
         SceneManager.LoadScene(level);
         //Instantiate(player1, playerPosition.position, Quaternion.identity);
     }
 }
 
 //and thats the globalControl Script
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class GlobalControl : MonoBehaviour {
 
     //private PlayerHealth pHealth;
     //private PlayerHealthSuit pHealthSuit;
     //public int playerStartHealth = 3;
     //public GameObject gameOverScreen;
     public static float health = 3;
 
     public static GlobalControl Instance;
 
     void Awake()
     {
         if (Instance == null)
         {
             DontDestroyOnLoad(gameObject);
             Instance = this;
         }
         else if (Instance != this)
         {
             Destroy(gameObject);
         }
     }
 
 }













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

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by LukasLicek · Jan 07, 2018 at 10:04 PM

@DuB86 EDIT from PC: I have code for a solution with static variable (as someone already suggested). This is a global storage in C#

 using System.Collections;
 using System.Collections.Generic;
 //deleted: using UnityEngine;
 
 //deleted: : MonoBehaviour (It does not need to be attached on object)
 public static class GlobalValueStorage {
     public static int playerHealth;
 }

How to use it:

 GlobalValueStorage.playerHealth = hp; //set value (safe)
 Debug.Log (GlobalValueStorage.playerHealth); //get value (load)
 //Values are not persistent between scenes

BEFORE EDIT:

You may find a way around it by setting the health of new object from old one and then delete it. Code looks like:

 Instantiate(playerRagdollLeft, playerPosition.position, Quaternion.identity).GetComponent<YourHealthScriptName>().SetLife(hp);
 //You get component and in that component create function:
 public void SetLife(int healht){
     hp = health;
 }

(Sorry for short answer, I'm on phone)

Comment
Add comment · Show 2 · Share
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
avatar image DuB86 · Jan 08, 2018 at 01:57 PM 0
Share

@LukasLicek

Great! thanks mate, it works! though I had to change some things e.g. the 2 health scripts had to substract life from the globalstorage value Example Code:

     public void ApplyDamage(float damage)
     {
         if (isDamageable)
         {
             GlobalValueStorage.playerHealth -= damage;
 
             GlobalValueStorage.playerHealth = $$anonymous$$athf.$$anonymous$$ax(0, GlobalValueStorage.playerHealth);
 
             healthSlider.value -= damage;
 
             if (!isDead)
             {
                 if (GlobalValueStorage.playerHealth == 0)
                 {
                     isDead = true;
                     Dying();
                 }
             }
 
             isDamageable = false;
             Invoke("ResetIsDamageable", 2);
         }
     }

Furthermore your script cant be attached to components in scene view. because it is abstract. For Comprehension the health value stored is scene specific?

avatar image LukasLicek DuB86 · Jan 08, 2018 at 02:13 PM 0
Share

@DuB86 The value transits between scenes! :)

It will not be saved when you will turn off game (or playmode) however.

However, I don't get the whole subtraction thing :D You can contact me via LukasLicek11@gmail.com or discord: Raven#2722 if you want :)

avatar image
0

Answer by ShadyProductions · Jan 07, 2018 at 01:48 PM

If you have 1 class with a non static field that means it's for that class only.

When you make 2 players and assign each the same script that means the class is instantiated twice.

Once for player one and player 2, so both objects have their own fields and properties.

What you want to do is make the health variable a static which means it's shared through all it's objects like so:

 public static float health = 3;

However, making it static means it won't be visible in the inspector any longer.

Comment
Add comment · Show 3 · Share
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
avatar image DuB86 · Jan 07, 2018 at 05:34 PM 0
Share

@ShadyProductions Still doesnt work, I tried to put static in playerhealth scripts, in globalcontrol script or in both, it doesnt work, I forgot to mention that I have two different names for the health scripts either playerNormal or playerSpaceSuit

avatar image DuB86 · Jan 07, 2018 at 09:55 PM 0
Share

@ShadyProductions thank you for your time, where do I put the static float? on the playerHealth script or in the global instance? if I make it in the global instance, I have to make everthing ...Tutorial.health... in the playerHealth scripts or on the playerHealth scripts or on both, tried every way, still the same problem. I forgot to mention my playerHealth Scripts also named differently for each Player

avatar image pako DuB86 · Jan 07, 2018 at 10:02 PM 0
Share

@DuB86 please don't post your comments as answers! You can also edit your original question to add more code, if it doesn't fit in the comment.

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

85 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

Related Questions

Understanding Prefabs + Player Spawn Points 2 Answers

Unity 5.6 doesn't instatiate object mantaining child position driven by animations 0 Answers

cannot build player while editor is importing assets or compiling scripts 7 Answers

Passing Parameters by Value or by Reference 2 Answers

Trying to have object spin within player and always face "up" relative to camera [example pics of what I'm trying to achieve in post]] 0 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