- Home /
Basic Question: Score System giving random numbers.
I'm quite a noob when it comes to scripting. I have this script added to some cube objects.
var buck : int = 1;
var target : Collider;
var ScoreBoard : GUIText;
function OnTriggerEnter(cubeTrigger : Collider)
{
if (cubeTrigger == target)
{
buck -= 1;
ScoreBoard.text = ("") + buck;
}
}
I've set the Buck to 3 in the inspector. Now when I hit a cube it gets -1 so it will be 2. But when I hit the next Cube it adds +2 or +3 sometimes. What am I doing wrong in this code?
You said you set Buck to 3 in the inspector, did you do it for all cubes or only one? and you should remove the () around ""
Answer by gregzo · Apr 12, 2012 at 02:57 PM
Try this :
ScoreBoard.text = buck.ToString();
And if I where you, I'd name ScoreBoard scoreBoard...
As for the strange variance of your buck, search all your scripts to see if it's not incremented elsewhere!
To help check if someone else is changing it, maybe add, just next to buck-=1;
: Debug.Log("hit, b="+buck);
. If the score changes and you don't see that line, someone else is changing it.
""+buck
is a pretty common shortcut to convert to string in C# -- I assume it's the same in unityScript.
Answer by Stardog · Apr 23, 2012 at 01:19 PM
You're correct about it not being the correct way to do it, because each cube will have its own "buck".
I would make a seperate "ScoreObject" with a ScoreScript attached, and have the buck/scoreboard variables in there. Also, it should "listen" for an AddToScore message, sent by the cubes, and then add or subract from the buck.
Use this messenger system. Put the files into Assets/Plugins.
Example:
ScoreScript on ScoreObject
using UnityEngine;
using System.Collections;
public class ScoreScript : MonoBehaviour {
public int buck = 1;
void OnEnable() {
Messenger<int>.AddListener("add_to_score", AddToScore);
}
void OnDisable() {
Messenger<int>.RemoveListener("add_to_score", AddToScore);
}
void AddToScore(int scoreToAdd)
{
buck += scoreToAdd;
}
}
Then on each cube, it would be like what you have now, except with a "scoreToAdd variable" (this would be -1 for your example) and put this inside the "if" statement:
Messenger<int>.Broadcast("add_to_score", scoreToAdd);
Then use a seperate GUIManager GameObject to display the "buck" in ScoreScript.
Basically, when a cube is hit, it will broadcast a message, and the ScoreObject will pick it up, then change the score to whatever was sent.
Your answer
Follow this Question
Related Questions
How to create a point/score system based on player performance. 2 Answers
Main Menu issues when restart 1 Answer
Scoring System 1 Answer
Health Regen Stop After Damage 1 Answer