Hello,
Before I dive into to Laser Defender section, I want to add Power/Fire Ball power-up to my game. I’ve found this topic related to what I want: [Solved]BoxCollider2D IsTrigger through the Script
I can call isTrigger true and get the power sometimes, but sometimes it doesn’t work and this line of error appears on Console: (For second time picking up the powerup, I always get the error)
MissingReferenceException: The object of type 'Block' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
Here is what I do:
- I have this static variable within Block class:
public static List<Block> blocks;
- This code on Start method of Block class to get array of Blocks
if (blocks == null || blocks.Count <= 0)
{
// written long-hand to make it easier to read
Block[] tempBlocks = FindObjectsOfType<Block>(); // gets the BrickPc game objects as an array
blocks = new List<Block>(tempBlocks); // initialise our list from an array
Debug.Log(blocks);
}
- And I remove destroyed blocks from array (Here may be where I am wrong):
private void DestroyBlock()
{
PlayBlockDestroyedSFX();
blocks.Remove(this);
Destroy(gameObject);
level.BlockDestroyed();
TriggerSparklesVFX();
PowerUpInstantiate();
}
- Here I start coroutine in Paddle class when powerup object collides with paddle:
if (other.gameObject.name == "powerUpPowerBall(Clone)")
{
StartCoroutine(PowerBall());
}
- Finally, I get isTrigger to true:
IEnumerator PowerBall()
{
LoadPowerBallSprite();
foreach (Block blocks in Block.blocks)
{
blocks.GetComponent<BoxCollider2D>().isTrigger = true;
}
yield return new WaitForSeconds(30);
LoadRegularBallSprite();
foreach (Block blocks in Block.blocks)
{
blocks.GetComponent<BoxCollider2D>().isTrigger = false;
}
}