Hi,
I want to count the number of destroyed objects in my scene. I hyve a code which destroys the shooted GameObject:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ShootableBox : MonoBehaviour {
public int currentHealth = 1;
//public int points = 0;
public void Damage(int damageAmount)
{
currentHealth -= damageAmount;
if (currentHealth <= 0)
{
gameObject.SetActive (false);
//points = points + 1;
}
}
}
The comments were my next step. How can I implimintate this Code?
This code is in every GameObject which can be Destroyed.
This is my Code I wrote to count the points:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PointsTextController : MonoBehaviour
{
public Text text;
public ShootableBox script;
void Update()
{
text.text = points;
}
}
I can’t give the script the Shootable Box Script whyever.
Please help me
no you dont, you have a code that disabled the objects shot. youre calling
gameObject.SetActive(false);
you need to call
GameObject.Destroy(object, timeBeforeDestroyed);
after the line where you destroy you can just
GameObject.Destroy(myObject , 0);
objectsDestroyed++;
Thanks for the answer bu I don’t understand…
What is time before destroyed and object and myobject. What has to be there?
You are on the right track. You want to count your points within the points text controller rather than the shootable box as this gets destroyed.
You only need this line of code to destroy (this means there will be fewer objects in your scene meaning better performance):
Destroy(this.gameObject);
So using altogether that looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ShootableBox : MonoBehaviour
{
public int currentHealth = 1;
[SerializeField] PointsTextController ptc;
public void Damage(int damageAmount)
{
currentHealth -= damageAmount;
if (currentHealth <= 0)
{
ptc.points++;
Destroy(this.gameObject);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PointsTextController : MonoBehaviour
{
public Text text;
public int points = 0;
void Update()
{
text.text = "" + points;
}
}
time before destroyed is how long until the object is deleted after the function calls delete.
leave it at 0 if you want it to be instant.
myObject is a placeholder for your object name. say you were deleting a coin after it was picked up, it would be
GameObject.Destroy(coin, 0)