Question by
Camilla_C · Dec 02, 2017 at 02:35 PM ·
inputtextinput.getkey
How to add score to text when button down?
New to Unity and trying to do my own code, but I stuffed up. I was trying to add a score to text when the jump was pressed but all I got was one's felling the whole screen whenever the jump key was pressed. How do I get the score to add whenever I use Jump?
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public Transform player;
public Text scoreText;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Jump"))
scoreText.text = ("1");
}
}
Comment
Answer by OpenMindStudios · Dec 02, 2017 at 04:17 PM
if you would like the score to add up then you will need to add` using UnityEngine; using UnityEngine.UI;
public class Score : MonoBehaviour {
public Transform player;
public Text scoreText;
public int score = 0; //This creates a variable called score and assigns it a default value of 0
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Jump")){
score ++; //everytime this if block is active it increments the score by 1
scoreText.text = (score); // sets the text to display the current score
}
}
}`
Thank you for helping me, I got an error: convert type int' to
string' and I fixed it with scoreText.text = (score).ToString();
Everything is working!