- Home /
How do you use collision to log number of hits, while duplicates are being destroyed?
using UnityEngine;
using System.Collections;
public class Brick : MonoBehaviour {
public int maxHits;
public int howManyHits;
// Use this for initialization
void Start () {
howManyHits = 0;
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter2D (Collision2D collision) {
howManyHits = howManyHits + 1;
print (howManyHits);
Destroy (gameObject);
if (howManyHits == 12) {
Application.LoadLevel ("YOU WON!");
}
}
}
It seems that when it gets destroyed the howManyHits resets. Can anyone help me with this?
Answer by Surprisejedi · May 04, 2015 at 05:09 PM
I need it because when it gets 12 hits it goes on to the next level
Please use comments ins$$anonymous$$d of answers to keep the conversation flow
Answer by $$anonymous$$ · May 04, 2015 at 11:26 PM
If you want to track how many of this type of gameObject have been destroyed then you need to make howManyHits a static variable.
Try changing this line
public int howManyHits;
with
public static int howManyHits;
You may want to refer to this for more info on the static modifier: https://msdn.microsoft.com/en-us/library/98f28cdx.aspx
Answer by bartm4n · May 04, 2015 at 04:46 PM
Destroying the object literally destroys it, so you lose any data associated with it. You would need to store the number of hits on a persistent object, like a game manager or state object of your own design.
I understand that you need it, but if you destroy the gameobject you lose the data attached to it. You will absolutely have to either not destroy the object or maintain the hit count somewhere else on a persistent object.
Answer by SwitchStance · May 04, 2015 at 11:29 PM
You are deleting the gameobject after it has been hit once. You can delete the gameobject after checking if it has been hit the max number of times.
if(howManyHits == maxHits)
{
Destroy(gameObject);
Application.LoadLevel("YOU WON!");
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613194743im_/https://answers.unity.com/themes/thub/images/avi.jpg)