HOW TO ADD ONSCREEN SCORE
HELLO, i have scoring script who count score when i collect coins.
#pragma strict
import UnityEngine.UI;
// JavaScript
var score = 0;
function OnTriggerEnter( other : Collider ) {
Debug.Log("OnTriggerEnter() was called");
if (other.tag == "coin")
{
Debug.Log("Other object is a coin");
score += 5;
Debug.Log("Score is now " + score);
Destroy(other.gameObject);
}
}
function OnGUI()
{
GUILayout.Label( "Score = " + score );
}
And i have one problem - how can i display my score on screen?
This code does show a score on screen. The OnGUI function should be working. Unless I'm misunderstanding the question, what is the problem?
score is counting, but it doesn't appear on screen
is the OnGUI function being called? Is this function just updating the label, not the text?
you will need to set the Rect of the label so that it appears on the screen, use screen.height and screen.width to find and set your initial position of the Rect and then add to it the size of the rect's height and width. Though using unity's built in UI system is much easier and will resize your UI components. https://unity3d.com/learn/tutorials/topics/user-interface-ui
Can you show me how it looks in script? I'm beginner in Unity
private float rectHeight = 10f; private float rectWidth = 10f; private float rectXInset = 100f; private float rectYInset = 100f; private Rect labelRect;
void OnEnable (){ labelRect = new Rect(Screen.Width - rectXInset, Screen.Height - rectYInset, rectWidth, rectHeight); }
this sets the rect to be 100 pixels in on the xAxis and 100 pixel in on the yAxis based on the screen's height and width. But if you are developing this on a mobile platform your going to be dealing with multiple devices with different screen heights and widths so you will either have to compensate for that by re-scaling the rect, or as i posted before use the UI system that will autoscale your UI components to the correct size (There should be a checkbox in the canvas scaler component which will allow the ui canvas to stretch to the current screen's size. I really suggest you look into this ins$$anonymous$$d of using the OnGUI function if you are new to scripting. Its well worth the few hours it takes to learn unity's UI system
Normally you don't need a Rect
inside the Label
contructor. Inserting a string
the Label
will be displayed in the upper left corner because it will be setup at x: 0
and y: 0
Where did you attach the script?
Your answer
Follow this Question
Related Questions
Problem with ScoreBoard in Ping Pong game 1 Answer
My score system doesn't display or work? Please help me! 1 Answer
How do I make a score system? 1 Answer
Easy Short kill score script not working 0 Answers
Write a score counter on an object 0 Answers