How to get 2D blocks to break after a certain amount of hits
Hey guys, I have been looking everywhere for a little tutorial about how to add "Strength" to a block so it takes a certain amount of hits (or clicks) to break from the main character. It's a 2D side-scroller game. Was wondering if anybody could help me out on this. Thanks in advance! Below is what I have so far. Also to add on, these "tiles" or "blocks" have a Box Collider 2D on them if that helps.
I saw somebody say: " For those who want to make the block have "hardness", you can attach a script to the tile prefabs. Then in the script create an int called strength. Then in the script for getting rid of the blocks have it subtract from the block's strength. Then have it so that once the block's strength is less than or equal to 0 have it destroy itself. Then add a number like 5 for dirt, 10-14 for stone, 14-18 for coal, 18-22 for iron, 22-26 for gold, 26-30 for diamond." ..... I didn't get it though.
Here is what I have and it does not work....the blocks I assign this script to still break with one hit. To be clear, I want the left mouse button to break the block, not the for character to run into the block and break it!
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TileStrength : MonoBehaviour { public int hitsNeeded = 4; public int hitsTaken; void OnCollisionEnter2D(Collision2D collisionInfo) { hitsTaken += 1; if (hitsTaken >= hitsNeeded) Destroy(gameObject); } }
UPDATE: Here is my updated code so far, any help would be appreciated! I am still so confused on how to make the left mouse click break the block after the certain amount of hits.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TileStrength : $$anonymous$$onoBehaviour
{
public int strength = 20;
}
enum Tile { Ground, Dirt, Stone, Lava, GoldOre, DiamondOre, Grass, Brick, Wood, GoldBlock, DiamondBlock, GlassBlock }
Your answer
![](https://koobas.hobune.stream/wayback/20220612211216im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
My character won't stop crouching, they dont stop crouchin 2 Answers
Can someone tell me how to restart the scene if my player hits two objects 2 Answers
destructible tilemap, destroying tiles through overlapcircle 1 Answer
Multiple Sprites, One Script, Randomization 1 Answer
Any one help me in this script? 0 Answers