Как получить одну из систем частиц?

У меня есть вражеский префаб (ZomBunny), в нем есть две частичные системы, которые должны воспроизводиться, когда враг поражен и когда враг умирает. Проблема, с которой я сталкиваюсь, заключается в том, что я могу получить доступ только к одной из систем частиц (HitParticle ) при использовании приведенного ниже кода.

Иерархия

введите здесь описание изображения

Здоровье врага

public class EnemyHealth : MonoBehaviour
{
    public int startingHealth = 100;          // The amount of health the enemy starts the game with.
    public int currentHealth;                    // The current health the enemy has.
    public float sinkSpeed = 2.5f;           // The speed at which the enemy sinks through the floor when dead.
    public int scoreValue = 10;               // The amount added to the player's score when the enemy dies.
    public AudioClip deathClip;              // The sound to play when the enemy dies.
    public GameObject text;

    Animator anim;                              // Reference to the animator.
    AudioSource enemyAudio;              // Reference to the audio source.
    ParticleSystem hitParticles;             // Reference to the particle system that plays when the enemy is damaged.
    ParticleSystem deathParticles;
    CapsuleCollider capsuleCollider;     // Reference to the capsule collider.
    bool isDead;                                  // Whether the enemy is dead.
    bool isSinking;                               // Whether the enemy has started sinking through the floor.

    void Awake ()
    {
        // Setting up the references.
        anim = GetComponent <Animator> ();
        enemyAudio = GetComponent <AudioSource> ();
        hitParticles = GetComponentInChildren <ParticleSystem> ();
        deathParticles = GetComponentInChildren <ParticleSystem> ();
        capsuleCollider = GetComponent <CapsuleCollider> ();

        // Setting the current health when the enemy first spawns.
        currentHealth = startingHealth;
    }

    void Update ()
    {
        // If the enemy should be sinking...
        if(isSinking)
        {
            // ... move the enemy down by the sinkSpeed per second.
            transform.Translate (-Vector3.up * sinkSpeed * Time.deltaTime);
        }
    }

    public void TakeDamage (int amount, Vector3 hitPoint)
    {
        // If the enemy is dead...
        if(isDead)
            // ... no need to take damage so exit the function.
            return;

        // Play the hurt sound effect.
        enemyAudio.Play ();

        // Reduce the current health by the amount of damage sustained.
        currentHealth -= amount;

        // Set the position of the particle system to where the hit was sustained.
        hitParticles.transform.position = hitPoint;

        // And play the particles.
        hitParticles.Play();

        // If the current health is less than or equal to zero...
        if(currentHealth <= 0)
        {
            // ... the enemy is dead.
            Death ();
        }
    }

    void Death ()
    {
        // The enemy is dead.
        isDead = true;

        // Turn the collider into a trigger so shots can pass through it.
        capsuleCollider.isTrigger = true;

        // Tell the animator that the enemy is dead.
        anim.SetTrigger ("Dead");

        deathParticles.Play();
        // Change the audio clip of the audio source to the death clip and play it (this will stop the hurt clip playing).
        enemyAudio.clip = deathClip;
        enemyAudio.Play ();
    }

    public void StartSinking ()
    {

        // Find and disable the Nav Mesh Agent.
        GetComponent <UnityEngine.AI.NavMeshAgent> ().enabled = false;

        // Find the rigidbody component and make it kinematic (since we use Translate to sink the enemy).
        GetComponent <Rigidbody> ().isKinematic = true;

        // The enemy should no sink.
        isSinking = true;

        // Increase the score by the enemy's score value.
        ScoreManager.score += scoreValue;

        // After 2 seconds destory the enemy.
        Destroy (gameObject, 2f);
    }
}

person Ved Sarkar    schedule 16.02.2017    source источник
comment
Можете ли вы загрузить изображение вашей иерархии, показывающее, где находятся частицы?   -  person Programmer    schedule 16.02.2017
comment
Обновлено путем добавления фото иерархии   -  person Ved Sarkar    schedule 16.02.2017


Ответы (1)


Когда вы делаете:

hitParticles = GetComponentInChildren<ParticleSystem>();
deathParticles = GetComponentInChildren<ParticleSystem>();

Unity получит первый компонент ParticleSystem для дочернего элемента. Вам нужен способ отличить, какой из них вы хотите. Есть много способов сделать это.

Если скрипт EnemyHealth прикреплен к игровому объекту ZomBunny:

Способ 1:

В ZomBunny GameObject hitParticles является дочерним элементом 0. Zombunny — дочерний элемент 1, а deathParticles — дочерний элемент 2.

Которые должны быть:

hitParticles = transform.GetChild(0).GetComponentInChildren<ParticleSystem>();
deathParticles = transform.GetChild(2).GetComponentInChildren<ParticleSystem>();

Метод 2:

Найдите оба GameObject, затем получите компоненты от каждого из них:

hitParticles = GameObject.Find("HitParticles").GetComponent<ParticleSystem>();
deathParticles = GameObject.Find("DeathParticles").GetComponent<ParticleSystem>();

Способ 3:

Используйте GetComponentsInChildren, который возвращает массив вместо GetComponentInChildren. Порядок непредсказуем, поэтому мы также должны проверить имя GameObject, чтобы убедиться, что это правильное ParticleSystem.

ParticleSystem[] ps = GetComponentsInChildren<ParticleSystem>();
for (int i = 0; i < ps.Length; i++)
{
    if (ps[i].gameObject.name == "HitParticles")
    {
        hitParticles = ps[i];
    }
    else if (ps[i].gameObject.name == "DeathParticles")
    {
        deathParticles = ps[i];
    }
}

Похоже, вы новичок в Unity. В этом случае лучше знать много вариантов, которые у вас есть.

person Programmer    schedule 16.02.2017
comment
Пробовал mrthod 1 и 2, первый метод работал как надо, а второй метод работает нормально, но выдает MissingReferenceException: объект типа 'ParticleSystem' был уничтожен, но вы все еще пытаетесь получить к нему доступ. Ваш сценарий должен либо проверить, является ли он нулевым, либо вы не должны уничтожать объект. error. - person Ved Sarkar; 16.02.2017
comment
Не могу сказать, почему это происходит. Используйте тот, который работает для вас. - person Programmer; 16.02.2017
comment
Большое спасибо за вашу помощь. - person Ved Sarkar; 17.02.2017
comment
Второй метод должен быть GetComponent, а не GetComponentInChildren. Я был сонным, когда я сделал этот ответ. Исправили и добро пожаловать! - person Programmer; 17.02.2017