Загрузка данных


Health.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 
public class Health : MonoBehaviour
{
    //Текущее здоровье игрока
    public int currenthealth = 10;
    //Максимальное здоровье игрока
    public int maxHealth = 10;
    //Компонент, отвечающий за проигрывание звуков
    public AudioSource audioSource;
    //Звуковой файл, содержащий звуковой эффект нанесения урона
    public AudioClip damageSound;
    //Метод, обрабатывающий нанесённый урон
    public void TakeDamage(int damage)
    {
        currenthealth -= damage;
 
        //Если здоровье ещё есть, то проигрывается звук нанесения урона
        if (currenthealth > 0)
        {
            audioSource.PlayOneShot(damageSound);
        }
        //Если здоровья нет, то перезапускается текущая сцена
        else
        {
            int sceneIndex = SceneManager.GetActiveScene().buildIndex;
            SceneManager.LoadScene(sceneIndex);
        }
    }
}
 


CoinsCounter.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class CoinsCounter : MonoBehaviour
{
    //Число собранных монет
    public int coins;
 
    //Метод, увеличивающий число монеток
    public void CollectCoins()
    {
        coins++;
    }
}

FireballAttack.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class FireballAttack : MonoBehaviour
{
    //Префаб огненного шара и параметр Transform точки атаки
    public GameObject fireballPrefab;
    public Transform attackPoint;
 
    void Update()
    {
        //Если игрок кликает левой кнопкой мыши, то создаётся огненный шар
        if (Input.GetMouseButtonDown(0))
        {
            Instantiate(fireballPrefab, attackPoint.position, attackPoint.rotation);
        }
    }
}


PlayerUI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
 
public class PlayerUI : MonoBehaviour
{
	public CoinsCounter coinsCount;
	public Health health;
	public TextMeshProUGUI coinsCounterText;
	public Slider healthSlider;
 
	void Update()
	{
		// Обновляем текст с кол-вом монеток
		coinsCounterText.text = coinsCount.coins.ToString();
		// Обновляем значение здоровья игрока
		healthSlider.maxValue = health.maxHealth;
		healthSlider.value = health.currenthealth;
	}
}
 
Enemy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Enemy : MonoBehaviour
{
    //Скорость движения врага
    public float speed;
    //Цель, к которой движется враг
    public Transform target;
    //Очки урона от атаки врагом игрока
    public int playerDamage = 2;
 
 
    void Update()
    {
        //Меняет каждый кадр позицию NPC на новую
        transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
 
        //Разворачивает каждый кадр NPC лицом к цели
        transform.LookAt(target.position);
    }
 
    //При столкновении врага с игроком второму наносится урон
    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            Health health = other.GetComponent<Health>();
            health.TakeDamage(playerDamage);
        }
    }
}


Coin.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Coin : MonoBehaviour
{
    void OnTriggerEnter(Collider other) {
 
        CoinsCounter coins = other.GetComponent<CoinsCounter>();
 
        //Количество монеток обновляется
        coins.CollectCoins();
 
        //Монетка, которую собрали, уничтожается
        Destroy(gameObject);
    }
}