- Home /
if 20 objects are destroyed...
Lads, I'd like to write a script in which once twenty block are destroyed a particle event is triggered. I'm just having a hard time figuring out the simplest way to write it. Any ideas?
Thx,
Stef
Increment a blocksDestroyed int when you destroy a block, and check for blocksDestroyed == 20 to instantiate your particle system maybe?
Answer by dannyskim · Dec 08, 2011 at 11:18 PM
Well, the simplest way would just be to increment a static value every time you call the Destroy() on the blocks.
using UnityEngine;
using System.Collections;
public class blockCounter : MonoBehaviour {
public static int blocksDestroyed = 0;
void Update()
{
if( blocksDestroyed == 20 )
{
// Play particle effect here;
}
}
}
From your other scripts before you call Destroy():
blockCounter.blocksDestroyed += 1;
Destroy( gameObject);
You can also use OnDestroy in the block script - this will work even if other objects destroy the blocks:
void OnDestroy(){
blockCounter.blocksDestroyed++;
}
It's not all that efficient to have an Update loop constantly checking a value which rarely changes, nor is it great practice to use public variables for this (since it could conceivably be accidentally altered). It would be much better to call a function which updates the blocksDestroyed variable and does something.
int blocksDestroyed = 0;
public void IncrementBlocksDestroyed ()
{
if (++blocksDestroyed == 20)
{
// whatever
}
}
Thx Eric. How does the script know that 'blocksDestroyed' is related to blocks being destroyed in game?... How is the relation created?
@Stef you need to learn basic scripting! You're replying to Eric's answer with a 3 months delay, way enough to learn about how you could implement his suggestion. Everytime you destroy a block, call the IncrementBlocksDestroyed function he suggested, that should be enough to "create a relation"!
Actually, I've been away for the last 3 months, and I'm just getting back to this now. Thanks.
Your answer
![](https://koobas.hobune.stream/wayback/20220613061920im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
destroy object 2 Answers
Pick up objects to destroy one object. 1 Answer
Destroying objects one at a time 1 Answer
destroy and create objects 1 Answer
Destroy All Objects In The Scene??? 1 Answer