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[i]);
}
}
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<ShieldController>(); // 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 */
}
}
}
Answer by Xilver266 · May 17, 2016 at 05:22 PM
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 :)
Answer by NoseKills · May 17, 2016 at 03:20 PM
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>();
Your answer
Follow this Question
Related Questions
Attach a shield to player (C#) 2 Answers
Trail effect for non-moving object 2 Answers
The bolt doesn't move 0 Answers
[Solved] I am trying to build a space sim/ shooter type game. 1 Answer
space shooter tutorial help 0 Answers