유니티 공부

적 죽을때 경험치와 랜덤 아이템 드랍 코드

원티어맨 2023. 2. 7. 11:15
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class EnemyHealth : MonoBehaviour
{
    #region Private Variables

    [SerializeField] private int startingHealth = 3;
    [SerializeField] private int currentHealth;
    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private Material matWhiteFlash;
    [SerializeField] private GameObject deathVFX;
    [SerializeField] private float setDefaultMatRestorefloat = .1f;
    private Material matDefault;
    private SpriteRenderer spriteRenderer;
    LevelSystem playerLevel;
     private GameObject player;
     public int enemyLevel;
    public float enemyXp;
    public float XpMultiplier;
    public TextMeshProUGUI text;
   

     
    public List<Transform> items = new List<Transform> ();

    #endregion

    private void Awake() {
        spriteRenderer = GetComponent<SpriteRenderer>();
        matDefault = spriteRenderer.material;
    }

    private void Start() {
        currentHealth = startingHealth;
        player = GameObject.FindGameObjectWithTag("Player");
        playerLevel = player.GetComponent<LevelSystem>();
        enemyLevel = Random.Range(1, playerLevel.level + 2);

         
        enemyXp = Mathf.Round(enemyLevel * 6 * XpMultiplier);
       
        text.text = "<color=red>Level: " + enemyLevel + "</color> \n XP: " + enemyXp;

       //Set Text Colour to Orange
        if (enemyLevel == playerLevel.level)
            text.text = "<color=orange>Level: " + enemyLevel + "</color> \n XP: " + enemyXp;
       
         
        if (enemyLevel < playerLevel.level)
        {
            float multiplier = 1 + (playerLevel.level - enemyLevel) * 0.1f;
           
            text.text = "<color=green>Level: " + enemyLevel + "</color> \n XP: " + Mathf.Round(enemyXp * multiplier);
        }
    }

    private void Update() {
        DetectDeath();
    }

    public void TakeDamage(int damage) {
        currentHealth -= damage;
        spriteRenderer.material = matWhiteFlash;
        StartCoroutine(SetDefaultMatRoutine(setDefaultMatRestorefloat));
    }

    private void DetectDeath() {
        if (currentHealth <= 0) {
           
            Instantiate(deathVFX, transform.position, transform.rotation);
             playerLevel.GainExperienceScalable(enemyXp, enemyLevel);
           
         
       
            dropRandomItem();
            Destroy(gameObject);
           
        }
        else{ }
    }

    private IEnumerator SetDefaultMatRoutine(float whiteFlashTime) {
        yield return new WaitForSeconds(whiteFlashTime);
        spriteRenderer.material = matDefault;
    }

public void dropRandomItem () {
        Instantiate(items[Random.Range(0,3)],transform.position,Quaternion.identity);
    }

   

}