Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

napisz mi kod unity dla paska zdrowia dla postaci

  1. User

    napisz mi kod unity dla paska zdrowia dla postaci

  2. Assistant

    Oto prosty kod paska zdrowia postaci dla Unity. Ten kod tworzy prosty system zdrowia z paskiem zdrowia, który zmniejsza się wraz ze zmniejszaniem zdrowia postaci.

    1. Stwórz nowy projekt 2D w Unity i dodaj postać (sprite) do sceny.
    2. Dodaj "UI Canvas" do sceny
    3. W "Canvas", dodaj pasek zdrowia (UI Slider)

    Teraz napiszemy C# skrypt dla paska zdrowia:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    
    public class HealthBar : MonoBehaviour
    {
        public Slider slider;
    
        public void SetMaxHealth(int health)
        {
            slider.maxValue = health;
            slider.value = health;
        }
    
        public void SetHealth(int health)
        {
            slider.value = health;
        }
    }
    

    Teraz napiszemy C# skrypt dla postaci, który będziemy nazywać "Character":

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class Character : MonoBehaviour
    {
        public int maxHealth = 100;
        public int currentHealth;
    
        public HealthBar healthBar;
    
        void Start()
        {
            currentHealth = maxHealth;
            healthBar.SetMaxHealth(maxHealth);
        }
    
        void OnTriggerEnter2D(Collider2D collision)
        {
            if (collision.CompareTag("trap"))
            {
                TakeDamage(10);
            }
        }
    
        void TakeDamage(int damage)
        {
            currentHealth -= damage;
            healthBar.SetHealth(currentHealth);
        }
    }
    

    Po napisaniu skryptów wykonaj następujące czynności:

    1. Przeciągnij skrypt "HealthBar" na Slider w Canvas
    2. Przeciągnij skrypt "Character" na twoją postać (sprite) w scenie
    3. Skonfiguruj "Health Bar" w skrypcie "Character" - przeciągnij obiekt Slider z Canvas do slotu "Health Bar" w skrypcie Character
    4. Ustaw "Max Health" w skrypcie "Character" na wartość, której potrzebujesz dla postaci

    W ten sposób stworzono prosty pasek zdrowia dla postaci w Unity. Pasek zdrowia zmniejsza się, gdy postać odbierze obrażenia od obiektu z tagiem "trap".

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.