Cant take another shield after took one

Hi, im scripting a shield system for space shooter and when i take a shield the first time the script works correctly but when take another shield, i get some errors.

void DestroyShields()
{
    GameObject[] shields = GameObject.FindGameObjectsWithTag("Shield");
    for (var i = 0; i < shields.Length; i++)
    {
        Destroy(shields*);*

}
}

void OnTriggerEnter(Collider other)
{

if (other.CompareTag(“ItemShield”))
{

Destroy(other.gameObject);
DestroyShields();

Instantiate(shieldController, transform.position, shieldController.transform.rotation);
GameObject shieldControllerObject = GameObject.FindWithTag(“Shield”);
shieldObject = shieldControllerObject.GetComponent(); // I think this is not reassigning the new shield

shieldObject.Blink(); //<- Here the code dont execute at second shield
shield = true;
shieldHealth2 = shieldHealth;

}
[…]
if (shield && shieldHealth2 > 0) {
Destroy(other.gameObject); // Destroys the enemy
shieldHealth2–;
shieldObject.Blink(); // ← Here the code fails
if (shieldHealth2 == 0) {
DestroyShields();
shield = false;
} else {
/* Game Over */
}
}
}

It’s a bit difficult to understand exactly what’s going on without knowing for example what is the name of the attached class. Is this ShieldController? What is the type of the variable ‘shieldController’ and is it a prefab assigned in inspector?

Anyways i think most of the problems are caused here.

DestroyShields();
Instantiate(shieldController, xxx, zzz);

GameObject shieldControllerObject = GameObject.FindWithTag("Shield");
shieldObject = shieldControllerObject.GetComponent<ShieldController>();

Destroy() doesn’t happen instantly. So if you are trying to first destroy all ‘shields’ then create a new one and find it with ‘FindWithTag(“Shield”);’, you might actually find one of the old shields marked for destruction.

If I understand right and you indeed try to FindWithTag() the thing you just instantiated, that’s unnecessary. Instantiate returns the new object you Instantiated so just take a reference to it

GameObject shieldControllerObject = (GameObject)Instantiate(shieldController, xxx, zzz);
shieldObject = shieldControllerObject.GetComponent<ShieldController>();

Hi

I solved changing this:

GameObject shieldControllerObject = GameObject.FindWithTag("Shield");
 shieldObject = shieldControllerObject.GetComponent<ShieldController>();

for this:

shieldObject = Instantiate(shieldController, transform.position, shieldController.transform.rotation) as ShieldController;

thanks for the clues, i was blocked :slight_smile: