- Home /
Use sprites as score/GUItext?
Hello. I have a sprite for each number 0-9. How would i use them to display the players current score?
Do i have to create an animation and then specify what frame to be on from the code? If so do i then have to pre-make every score from 0-whateever? Or maybe dynamically change the sprite of an gameObject?
Are there any better way to approach this?
Thanks!
You'll have to keep a numeric score somewhere and then parse it to know which sprite to display in each position. Why not just use that numeric value in GUIText with font properties tweaked to your liking?
Answer by rosdi · May 18, 2014 at 04:43 PM
This is probably a late answer, but anyway here is how I do it. You need to have your score sprites named "0", "1", ... "9" in the game somewhere outside of the camera view otherwise this code will not work.
This code can be improved further for better performance.. but I for my game it is unnecessary since I don't have too many objects on the screen.
public class ScoreManager : MonoBehaviour {
private const float SPRITE_WIDTH = 0.07f;
private const string SPRITE_TAG = "SCORE_SPRITE"; //http://answers.unity3d.com/questions/33597/is-it-possible-to-create-a-tag-programmatically.html
void Start() {
}
public void UpdateScore (int score) {
//remove previous scores
GameObject[] oldScoreDigits = GameObject.FindGameObjectsWithTag(SPRITE_TAG);
foreach (var oldScoreDigit in oldScoreDigits) {
Destroy(oldScoreDigit);
}
string scoreStr = score.ToString();
for (int i = 0; i < scoreStr.Length; i++)
{
GameObject digit = (GameObject)Instantiate(GameObject.Find(scoreStr.Substring(i,1)));
digit.tag = SPRITE_TAG; //tag this object for easy removal
digit.transform.parent = this.transform;
digit.transform.localPosition = new Vector3(i * 0.08f, 0, transform.position.z);
}
//center score to top screen
Vector3 pos = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width/2f, Screen.height * 0.96f, Camera.main.nearClipPlane));
pos.x -= scoreStr.Length*SPRITE_WIDTH/2f;
transform.position = pos;
}
}
Put this script on a GameObject under your main camera. That way the score is always visible on the screen. As shown below.. this script is attached to Score game object under main camera.
it the code you state SPRITE_WIDTH = 0.07f;
i got sprites with width size 105 pixels how is that as float ? And I am having problem on the way to use this to pass the score so it will "print" on screen.
any suggestions?
Your answer
Follow this Question
Related Questions
Score going up every second 1 Answer
What is the best way to show (Instantiate) a GUIText at the position of a GameObject? 3 Answers
Show score when enemy is destroyed C# 1 Answer
I used a GUIText to show the score in my game but it doesn't show my true results 0 Answers
Picking up an Item and telling you how many you have 1 Answer