Как сделать так чтобы вначале игры было максимальное здоровье и каждый уровень(сцену) здоровье не обновлялось?
я использовал сохранения (PlayerPrefs) взял туториал с ютуба
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System; public class PlayerMove : MonoBehaviour { [SerializeField] float gravity = 50; [SerializeField] Text HpText; [SerializeField] float jumpForce = 30; [SerializeField] private Text scoreText; //ссылка на текст подсчет очков [SerializeField] private Text scoreTextpremium; //ссылка на текст подсчет особых очков private bool facingRight = true; private float moveInput; private int scoreCount = 0; private int scoreCountP = 0; private Rigidbody2D rb; private int health; public float speed = 10f; private Vector2 moveVector; Vector3 direction; Animator anim; GameObject Player; public void ChangeHealth(int count) { health = health += count; if (health > 100) { health = 100; } if (health <= 0) { LoadSceneLose(); } HpText.text = health.ToString(); } void Start() { anim = GetComponent<Animator>(); PlayerPrefs.GetInt("health", health); ChangeHealth(100); } void Awake() { rb = GetComponent<Rigidbody2D>(); } void FixedUpdate() { if(facingRight == false && moveInput > 0) { Flip(); } else if(facingRight == true && moveInput <0) { Flip(); } moveVector.x = Input.GetAxis("Horizontal"); moveVector.y = Input.GetAxis("Vertical"); rb.MovePosition(rb.position + moveVector * speed * Time.deltaTime); direction.y -= gravity * Time.deltaTime; Flip(); } public void LoadSceneOne() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } public void LoadSceneLose() { SceneManager.LoadScene(5); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.tag == "hleb") { Destroy(collision.gameObject); health += 10; HpText.text = health.ToString();//обновляем UIText PlayerPrefs.SetInt("health", health); } if (collision.tag == "premium") { Destroy(collision.gameObject); health += 50; HpText.text = health.ToString();//обновляем UIText PlayerPrefs.SetInt("health", health); } if (collision.tag == "door") { LoadSceneOne(); } if (collision.tag == "dangerhleb") { GetComponent<PlayerMove>().ChangeHealth(-50); StartCoroutine(Idle()); PlayerPrefs.SetInt("health", health); } if (collision.tag == "platform") { StartCoroutine(Idle()); } } private void OnTriggerExit2D(Collider2D collision) { if (collision.tag == "dangerhleb") { StopCoroutine(Idle()); } } private void OnCollisionStay2D(Collision2D other) { if(other.collider.tag == "boss") { GetComponent<PlayerMove>().ChangeHealth(-1); PlayerPrefs.SetInt("health", health); } if(other.collider.tag == "enemy") { ChangeHealth(-1); PlayerPrefs.SetInt("health", health); } if (other.collider.tag == "platform") { StartCoroutine(Idle()); PlayerPrefs.SetInt("health", health); } } IEnumerator Idle() { while(true) { yield return new WaitForSeconds(1f); GetComponent<PlayerMove>().ChangeHealth(-3); } } void Flip() { if(Input.GetAxis("Horizontal") > 0) { transform.localRotation = Quaternion.Euler(0, 0, 0); } if(Input.GetAxis("Horizontal") < 0) { transform.localRotation = Quaternion.Euler(0, 180, 0); } } } |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System; public class PlayerMove : MonoBehaviour { [SerializeField] float gravity = 50; [SerializeField] Text HpText; [SerializeField] float jumpForce = 30; [SerializeField] private Text scoreText; //ссылка на текст подсчет очков [SerializeField] private Text scoreTextpremium; //ссылка на текст подсчет особых очков private bool facingRight = true; private float moveInput; private int scoreCount = 0; private int scoreCountP = 0; private Rigidbody2D rb; private int health; public float speed = 10f; private Vector2 moveVector; Vector3 direction; Animator anim; GameObject Player; public void ChangeHealth(int count) { health = health += count; if (health > 100) { health = 100; } if (health <= 0) { LoadSceneLose(); } HpText.text = health.ToString(); } void Start() { anim = GetComponent<Animator>(); PlayerPrefs.GetInt("health", health); ChangeHealth(100); } void Awake() { rb = GetComponent<Rigidbody2D>(); } void FixedUpdate() { if(facingRight == false && moveInput > 0) { Flip(); } else if(facingRight == true && moveInput <0) { Flip(); } moveVector.x = Input.GetAxis("Horizontal"); moveVector.y = Input.GetAxis("Vertical"); rb.MovePosition(rb.position + moveVector * speed * Time.deltaTime); direction.y -= gravity * Time.deltaTime; Flip(); } public void LoadSceneOne() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } public void LoadSceneLose() { SceneManager.LoadScene(5); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.tag == "hleb") { Destroy(collision.gameObject); health += 10; HpText.text = health.ToString();//обновляем UIText PlayerPrefs.SetInt("health", health); } if (collision.tag == "premium") { Destroy(collision.gameObject); health += 50; HpText.text = health.ToString();//обновляем UIText PlayerPrefs.SetInt("health", health); } if (collision.tag == "door") { LoadSceneOne(); } if (collision.tag == "dangerhleb") { GetComponent<PlayerMove>().ChangeHealth(-50); StartCoroutine(Idle()); PlayerPrefs.SetInt("health", health); } if (collision.tag == "platform") { StartCoroutine(Idle()); } } private void OnTriggerExit2D(Collider2D collision) { if (collision.tag == "dangerhleb") { StopCoroutine(Idle()); } } private void OnCollisionStay2D(Collision2D other) { if(other.collider.tag == "boss") { GetComponent<PlayerMove>().ChangeHealth(-1); PlayerPrefs.SetInt("health", health); } if(other.collider.tag == "enemy") { ChangeHealth(-1); PlayerPrefs.SetInt("health", health); } if (other.collider.tag == "platform") { StartCoroutine(Idle()); PlayerPrefs.SetInt("health", health); } } IEnumerator Idle() { while(true) { yield return new WaitForSeconds(1f); GetComponent<PlayerMove>().ChangeHealth(-3); } } void Flip() { if(Input.GetAxis("Horizontal") > 0) { transform.localRotation = Quaternion.Euler(0, 0, 0); } if(Input.GetAxis("Horizontal") < 0) { transform.localRotation = Quaternion.Euler(0, 180, 0); } } }
в итоге вышли такие ошибки
Дополнительно:
vitek22 https://qna.habr.com/help/rules#3.8
Ответы:
Исходя только из кода получается, что:
1-я ошибка в 37 строке у тебя возможно не назначена ссылка на текстовый объект TMPro, к которому обращается скрипт.
2-я ошибка скрипт не может найти на этом объекте компонент Rigidbody, который ты прописал инициализировать в Awake().
- в первой ошибке оно не должно быть ссылки на ТМЗро
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос

Для того чтобы достичь такой функциональности в игре, где максимальное здоровье будет установлено в начале игры и не будет обновляться на каждом уровне или сцене, можно использовать переменную для хранения максимального здоровья и обновлять только текущее здоровье игрока.
Пример кода на языке PHP:
class Player { private $maxHealth; private $currentHealth; public function __construct($maxHealth) { $this->maxHealth = $maxHealth; $this->currentHealth = $maxHealth; } public function setHealth($health) { if ($health maxHealth) { $this->currentHealth = $health; } else { $this->currentHealth = $this->maxHealth; } } public function getHealth() { return $this->currentHealth; } } // Создание игрока с максимальным здоровьем 100 $player = new Player(100); // Установка текущего здоровья игрока $player->setHealth(100); // Получение текущего здоровья игрока echo $player->getHealth(); // Выведет 100 // При переходе на новый уровень или сцену, текущее здоровье игрока не будет обновляться
В данном примере создается класс Player, который имеет свойства maxHealth и currentHealth. В конструкторе класса устанавливается максимальное здоровье игрока, которое не изменяется. Метод setHealth позволяет установить текущее здоровье игрока, при этом проверяется, чтобы оно не превышало максимальное здоровье. Метод getHealth возвращает текущее здоровье игрока.
Таким образом, при создании игрока устанавливается максимальное здоровье, которое не меняется на протяжении всей игры, а текущее здоровье можно обновлять при необходимости, не превышая установленный лимит.