-4

I want simply to destroy a deactivated instance of a Quad prefab (hp bar) , am able to destroy activated ones with :

private GameObject correspondingHpBar; 
private string correspondingHpBarName;

void Start() 
{ 
    correspondingHpBarName = "hpBar1" 
}

void Update()
{
    correspondingHpBar = GameObject.Find (correspondingHpBarName); 
    if (shipHp <= 0)
    {
        Destroy (correspondingHpBar); 
        Destroy (gameObject); 
    }
}

This doesn't work with the deactivated objects, i googled hard but failed to find an answer.

Kryptos
  • 875
  • 8
  • 19
Huskarnov
  • 9
  • 3
  • 3
    If you are using the Unity game engine please add the tag [tag:unity3d] (even for 2d games), if you are not using Unity please find the tag for whatever engine you are using. Also "It doesn't work" is not enough information, [edit your question](http://stackoverflow.com/posts/30537521/edit) and explain how it does not work. Do you get a exception? does it not behave in the expected way? – Scott Chamberlain May 29 '15 at 20:27

1 Answers1

0

Deactivated object don't have their Start or Update method called (nor any coroutine for that matter). In fact when an object is deactivated it is like its own time is frozen.

What you could do is create a method that does the destruction and find a way to call it from another script (for example a kind of controller that keeps reference to all HP bars in your scene).

The following is some pseudo-code (didn't check if it compiles, but you should adapt it anyway):

// in script for HP bar
public Boolean TryDestroy()
{
    if (shipHp <= 0)
    {
        Destroy (correspondingHpBar); 
        Destroy (gameObject); 
        return true;
    }
    return false;
}

// in another script
private List<HPBar> _allHPBars;
void Awake()
{
    _allHPBars = new List<HPBar>(FindObjectsOfType(typeof(HPBar)));
}

void Update()
{
    var destroyedHPBars = new List<HPBar>();
    foreach (var hpBar in _allHPBars)
    {
        if (hpBar.TryDestroy())
        {
            destroyedHPBars .Add(hpBar);
        }
    }
    foreach (var destroyedBar in destroyedHPBars)
    {
        _allHPBars.Remove(destroyedBar);
    }
}
Kryptos
  • 875
  • 8
  • 19