Health && Damage script

Форум для самых маленьких, а так же тех, кому недосуг читать справку самостоятельно.

Health && Damage script

Сообщение GoldmiX 03 мар 2019, 16:17

Здравствуйте, почему не отрабатывают скрипты? Дамаг не наноситься.. PlayerHealth загрузил в playerShip Объект, а в префаб Enemy EnemyAttack...

playerHealth

Синтаксис:
Используется csharp
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
 
public class PlayerHealth : MonoBehaviour
{
    public int startingHealth = 100;                            // The amount of health the player starts the game with.
    public int currentHealth;                                   // The current health the player has.
    public Slider healthSlider;                                 // Reference to the UI's health bar.
    public Image damageImage;                                   // Reference to an image to flash on the screen on being hurt.
    public AudioClip deathClip;                                 // The audio clip to play when the player dies.
    public float flashSpeed = 5f;                               // The speed the damageImage will fade at.
    public Color flashColour = new Color(1f, 0f, 0f, 0.1f);     // The colour the damageImage is set to, to flash.
 
 
    Animator anim;                                              // Reference to the Animator component.
    AudioSource playerAudio;                                    // Reference to the AudioSource component.
    PlayerScript playerMovement;                              // Reference to the player's movement.
    LaserScript playerShooting;                              // Reference to the PlayerShooting script.
    bool isDead;                                                // Whether the player is dead.
    bool damaged;                                               // True when the player gets damaged.
 
 
    void Awake()
    {
        // Setting up the references.
        anim = GetComponent<Animator>();
        playerAudio = GetComponent<AudioSource>();
 
        // Set the initial health of the player.
        currentHealth = startingHealth;
    }
 
 
    void Update()
    {
        // If the player has just been damaged...
        if (damaged)
        {
            // ... set the colour of the damageImage to the flash colour.
            damageImage.color = flashColour;
        }
        // Otherwise...
        else
        {
            // ... transition the colour back to clear.
            damageImage.color = Color.Lerp(damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
        }
 
        // Reset the damaged flag.
        damaged = false;
    }
 
 
    public void TakeDamage(int amount)
    {
        // Set the damaged flag so the screen will flash.
        damaged = true;
 
        // Reduce the current health by the damage amount.
        currentHealth -= amount;
 
        // Set the health bar's value to the current health.
        healthSlider.value = currentHealth;
 
        // Play the hurt sound effect.
        playerAudio.Play();
 
        // If the player has lost all it's health and the death flag hasn't been set yet...
        if (currentHealth <= 0 && !isDead)
        {
            // ... it should die.
            Death();
        }
    }
 
 
    void Death()
    {
        // Set the death flag so this function won't be called again.
        isDead = true;
 
        // Tell the animator that the player is dead.
        anim.SetTrigger("Die");
 
        // Set the audiosource to play the death clip and play it (this will stop the hurt sound from playing).
        playerAudio.clip = deathClip;
        playerAudio.Play();
 
        // Turn off the movement and shooting scripts.
        playerMovement.enabled = false;
        playerShooting.enabled = false;
    }
}


EnemyAttack

Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;


public class EnemyAttack : MonoBehaviour
{
    public float timeBetweenAttacks = 0.5f;     // The time in seconds between each attack.
    public int attackDamage = 10;               // The amount of health taken away per attack.


    Animator anim;                              // Reference to the animator component.
    GameObject player;                          // Reference to the player GameObject.
    PlayerHealth playerHealth;                  // Reference to the player's health.
    EnemyScript enemyHealth;                    // Reference to this enemy's health.
    bool playerInRange;                         // Whether player is within the trigger collider and can be attacked.
    float timer;                                // Timer for counting up to the next attack.


    void Awake()
    {
        // Setting up the references.
        player = GameObject.FindGameObjectWithTag("playerShip");
        playerHealth = player.GetComponent<PlayerHealth>();
        enemyHealth = GetComponent<EnemyScript>();
        anim = GetComponent<Animator>();
    }


    void OnTriggerEnter(Collider other)
    {
        // If the entering collider is the player...
        if (other.gameObject == player)
        {
            // ... the player is in range.
            playerInRange = true;
        }
    }


    void OnTriggerExit(Collider other)
    {
        // If the exiting collider is the player...
        if (other.gameObject == player)
        {
            // ... the player is no longer in range.
            playerInRange = false;
        }
    }


    void Update()
    {
        // Add the time since Update was last called to the timer.
        timer += Time.deltaTime;

        // If the timer exceeds the time between attacks, the player is in range and this enemy is alive...
        if (timer >= timeBetweenAttacks && playerInRange && enemyHealth.Enemyhealth > 0)
        {
            // ... attack.
            Attack();
        }

        // If the player has zero or less health...
        if (playerHealth.currentHealth <= 0)
        {
            // ... tell the animator the player is dead.
            anim.SetTrigger("PlayerDead");
        }
    }


    void Attack()
    {
        // Reset the timer.
        timer = 0f;

        // If the player has health to lose...
        if (playerHealth.currentHealth > 0)
        {
            // ... damage the player.
            playerHealth.TakeDamage(attackDamage);
        }
    }
}
GoldmiX
UNец
 
Сообщения: 7
Зарегистрирован: 03 мар 2019, 16:03

Re: Health && Damage script

Сообщение Saltant 03 мар 2019, 16:31

Расставь Debug.Log("text"); и посмотри где не отрабатывает.
Я на Google Play _https://play.google.com/store/apps/developer?id=Saltant
Аватара пользователя
Saltant
Адепт
 
Сообщения: 2235
Зарегистрирован: 09 окт 2018, 16:40
Откуда: Химки
  • Сайт

Re: Health && Damage script

Сообщение GoldmiX 03 мар 2019, 19:16

Saltant писал(а):Расставь Debug.Log("text"); и посмотри где не отрабатывает.


UnityException: Tag: playerShip is not defined.
EnemyAttack.Awake () (at Assets/Scripts/EnemyAttack.cs:22)
GoldmiX
UNец
 
Сообщения: 7
Зарегистрирован: 03 мар 2019, 16:03

Re: Health && Damage script

Сообщение GoldmiX 03 мар 2019, 19:24

Почему не видит объект?
GoldmiX
UNец
 
Сообщения: 7
Зарегистрирован: 03 мар 2019, 16:03

Re: Health && Damage script

Сообщение Saltant 03 мар 2019, 19:29

GoldmiX писал(а):Почему не видит объект?

Если таг выставлен на объект и не находит, значит объекта еще нет. Перенеси поиск из авейка в старт.
Я на Google Play _https://play.google.com/store/apps/developer?id=Saltant
Аватара пользователя
Saltant
Адепт
 
Сообщения: 2235
Зарегистрирован: 09 окт 2018, 16:40
Откуда: Химки
  • Сайт

Re: Health && Damage script

Сообщение GoldmiX 03 мар 2019, 19:35

Вроде ошибок нет, но теперь в этой части..

UnityEngine.Debug:Log(Object)
EnemyAttack:Update() (at Assets/Scripts/EnemyAttack.cs:73)
GoldmiX
UNец
 
Сообщения: 7
Зарегистрирован: 03 мар 2019, 16:03

Re: Health && Damage script

Сообщение GoldmiX 03 мар 2019, 19:38

Есть подозрение, что не видит EnemyHealth, который в скрипте EnemyScript.. и хранится как public int...

public class EnemyScript : MonoBehaviour
{

public int Enemyhealth = 2;
GoldmiX
UNец
 
Сообщения: 7
Зарегистрирован: 03 мар 2019, 16:03

Re: Health && Damage script

Сообщение GoldmiX 03 мар 2019, 19:50

System.NullReferenceException: Object reference not set to an instance of an object
at EnemyAttack.Update () [0x00048] in C:\Users\User\Documents\New Unity Project (2)\Assets\Scripts\EnemyAttack.cs:68
GoldmiX
UNец
 
Сообщения: 7
Зарегистрирован: 03 мар 2019, 16:03

Re: Health && Damage script

Сообщение GoldmiX 03 мар 2019, 20:02

Можно же поменять object на transform? так ошибок нету, но хп при столкновении все равно не убавляются
GoldmiX
UNец
 
Сообщения: 7
Зарегистрирован: 03 мар 2019, 16:03

Re: Health && Damage script

Сообщение seaman 03 мар 2019, 22:34

Строчки приводите, где ошибки, а то Вы скрипт поправили и по номеру строки теперь не так просто найти.
Я так понял, что на Игроке нет скрипта PlayerHealth, но возможно все же неверно вычислил строку с ошибкой.
seaman
Адепт
 
Сообщения: 8352
Зарегистрирован: 24 янв 2011, 12:32
Откуда: Самара

Re: Health && Damage script

Сообщение Friend123 04 мар 2019, 00:23

Это, лично у меня, самая распространенная ошибка, объект не успел инициализироваться, либо он не назначен в паблик переменной, обычно пара минут времени и всё понятно
Аватара пользователя
Friend123
Старожил
 
Сообщения: 701
Зарегистрирован: 26 фев 2012, 22:12
Откуда: Тверь
  • ICQ


Вернуться в Почемучка

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 25