Hi! So we’ve made a code in unity that could destroy an object and at the same time… add score:
var Score3Dtext: TextMesh;
private var score: int=1000;
function Update () {
if(Input.GetMouseButtonDown(0))
{
var hit: RaycastHit;
var ray: Ray=Camera.main.ScreenPointToRay (Input.mousePosition);
if(Physics.Raycast(ray, hit))
{
if(hit.transform.gameObject == this.gameObject)
{
Destroy(this.gameObject);
score += 1;
Score3Dtext.text= "Score: " + score.ToString();
}
}
}
}
so… We’ve dragged it in our object. Once we click the object, it destroys and add 1 to the score… it becomes 1001, but whenever we click another object, it stays the same… 1001 but it will be destroyed, our only problem is about the scoring. please help! thank you.
You cannot keep the track of a score on the objects that are going to be destroyed, whenever new object spawns, your score is 1000 again, but you see 1001 because you are not updating it until you destroy that object, so when you do , it goes back to 1001.
You will have to make a separate script that will hold you score, and access it from this script.
The way i would do it is make a tag called “ScoreBoard” and put it on your 3dText.
make new script called “Scoring” and add it to that 3dtext:
#pragma strict
var Score3dText: TextMesh;
var score=1000;
function Update(){
Score3dText.text="Score : " + score.ToString();
}
It will keep your score. Now you need to access it from your object that will be destroyed. This is your script slightly modified:
private var Score3Dtext: GameObject;
function Start(){
Score3Dtext= GameObject.FindGameObjectWithTag("ScoreBoard") ;
}
function Update () {
if(Input.GetMouseButtonDown(0))
{
var hit: RaycastHit;
var ray: Ray=Camera.main.ScreenPointToRay (Input.mousePosition);
if(Physics.Raycast(ray, hit))
{
if(hit.transform.gameObject == this.gameObject)
{
Score3Dtext.GetComponent(Scoring).score+=1;
Destroy(this.gameObject);
}
}
}
}
Dont forget to drag your 3dtext onto its Scoring script. Everything will work fine now.