scoreText.text not working in unity - c#

"Score:" is not being displayed on unity ide.i have tried a lot and nothing seems to be working and not getting output as expected.Thankyou.Sorry for bad English.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class uiManager : MonoBehaviour {
public Text scoreText;
int score;
// Use this for initialization
void Start () {
score = 0;
}
void score_view()
{
score = move.score;
Debug.Log("uiManager Score:"+score);
scoreText.text = "Score:"+score;
}
// Update is called once per frame
void Update ()
{
score_view();
}
}

Update is called once per frame, if your GameObject is active, and your script is Enabled.
Moreover, your game should be running.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.Update.html
You can check this states with these variables:
this.gameObject.activeSelf
this.enabled

Related

How to modify UI text via script?

A simple question: I'm trying to modify UI text (TextMeshPro if that makes any difference) via C# script. I am using the following code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Coins : MonoBehaviour
{
public Text coins;
void Start()
{
coins = GetComponent<Text>();
}
void Update()
{
coins.text = "text";
}
}
I've done a similar thing in Unity 2018 (I'm currently using Unity 2020.2) and it worked there.
For some reason it doesn't work here though. I would appreciate any help.
Changing text in TMP is practicly the same, but you need to add "using TMPro;" and also change variable type. The code should look like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Coins : MonoBehaviour
{
public TMP_Text coins;
void Start()
{
coins = GetComponent<TextMeshProUGUI>();
}
void Update()
{
coins.text = "text";
}
}
To modify TextMeshPro components, you have to use TMP_Text class.
public class Coins : MonoBehaviour
{
public TMP_Text coins;
void Start()
{
coins = GetComponent<TMP_Text>();
}
void Update()
{
coins.text = "text"; //or coins.SetText(“text”);
}
}
You need to reference the tmp text component instead of the normal Unity text one:
Instead of GetComponent<Text>(); do GetComponent<TextMeshProUGUI>();
Of course don’t forget:
using TMPro;
on top of your code.

Setting levels in a quiz game

This is my first post to Stack Overflow so please be gentle. I have followed the video tutorial at https://learn.unity.com/tutorial/live-session-quiz-game-1 and have been able to successfully modify it so that images are shown as questions instead of text. The next step for me is to divide my game into Levels. I have added the appropriate extra 'Rounds' in the DataController object referred to at the end of video 3 start of video 4 so that it now looks like this:
So here is the question, if I want to add a set of buttons to a Levels page, and then add an OnClick event to each, how do I point that OnClick event specifically to the set of questions for each Level? I think I need to point the onClick at a script passing a variable that is the level number, but not sure how to do it and so far searches of StackOverflow and YouTube haven't really helped?
EDIT
I have done the following and I seem to be a lot closer:
Created a new scene called LevelSelect and added the buttons I need for the levels to it;
I created a script in the scene called LevelSelectController and to this I added the button registration script provided by Lothan;
I registered the buttons as suggested via drag and drop;
I created a Function within the LevelSelectController script called StartGame, this had one line:
Debug.Log("Button pressed is: Level " + (setLevel + 1));
I ran the script and the buttons responded as expected;
All I am struggling with now his how to get the button press to pass the integer for the level number to the allRoundData variable in the DataController. The code for each script looks like this:
DataController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class DataController : MonoBehaviour
{
public RoundData[] allRoundData;
public int currentLevel;
// Start is called before the first frame update
void Start()
{
DontDestroyOnLoad (gameObject);
SceneManager.LoadScene ("MenuScreen");
}
public RoundData GetCurrentRoundData()
{
return allRoundData [currentLevel];
}
// Update is called once per frame
void Update()
{
}
}
LevelSelectController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LevelSelectController : MonoBehaviour
{
public List<Button> buttonsList = new List<Button>();
private DataController dataController;
public void StartGame(int setLevel)
{
Debug.Log("Button pressed is: Level " + (setLevel + 1));
}
}
GameController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour
{
public Text questionText;
public Image questionImage;
public SimpleObjectPool answerButtonObjectPool;
public Transform answerButtonParent;
private DataController dataController;
private RoundData currentRoundData;
private QuestionData[] questionPool;
private bool isRoundactive;
private float timeRemaining;
private int questionIndex;
private int playerScore;
private List<GameObject> answerButtonGameObjects = new List<GameObject> ();
// Start is called before the first frame update
void Start()
{
dataController = FindObjectOfType<DataController> ();
currentRoundData = dataController.GetCurrentRoundData ();
questionPool = currentRoundData.questions;
timeRemaining = currentRoundData.timeLimitInSeconds;
playerScore = 0;
questionIndex = 0;
ShowQuestion ();
isRoundactive = true;
}
private void ShowQuestion()
{
RemoveAnswerButtons ();
QuestionData questionData = questionPool[questionIndex];
questionText.text = questionData.questionText;
questionImage.transform.gameObject.SetActive(true);
questionImage.sprite = questionData.questionImage;
for (int i = 0; i < questionData.answers.Length; i++)
{
GameObject answerButtonGameObject = answerButtonObjectPool.GetObject();
answerButtonGameObjects.Add(answerButtonGameObject);
answerButtonGameObject.transform.SetParent(answerButtonParent);
AnswerButton answerButton = answerButtonGameObject.GetComponent<AnswerButton>();
answerButton.Setup(questionData.answers[i]);
}
}
private void RemoveAnswerButtons()
{
while (answerButtonGameObjects.Count > 0)
{
answerButtonObjectPool.ReturnObject(answerButtonGameObjects[0]);
answerButtonGameObjects.RemoveAt(0);
}
}
// Update is called once per frame
void Update()
{
}
}
How do I now pass the value of setLevel in LevelSelectController to currentLevel in the DataController script?
Welcome to StackOverflow!
You can do it using different ways, but one could be:
First register all the buttons:
List<Button> buttonsList = new List<Button>();
Then assign to each button the behaviour to do when onClick (registering the listener) passing the info of the corresponding DataController:
for(int i = 0; i < buttonsList.Count; i++)
{
buttonsList[i].onClick.AddListener(() => SetLevel(DataController.allRoundData[i]))
}
There are some leaps of faith in this current answer cause I don't know about your code, but if you have doubts, comment and I'll update the answer ^^
With a little extra research I was able to use a static variable along with Lothan's suggestion to get to the solution. Here is the modified code:
LevelSelectController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LevelSelectController : MonoBehaviour
{
static public int currentLevel
public List<Button> buttonsList = new List<Button>();
void Start()
{
for(int i = 0; i < buttonsList.Count; i++)
{
int levelNum = i;
buttonsList[i].onClick.AddListener(() => {currentLevel = levelNum;});
}
}
public void StartLevel()
{
SceneManager.LoadScene ("Game");
}
}
And only one edit needed in the Start() of GameController.cs, from
currentRoundData = dataController.GetCurrentRoundData ();
to:
currentRoundData = dataController.GetCurrentRoundData (LevelSelectController.currentLevel);

TextMeshPro Text not changing, console is giving rapid errors

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Num : MonoBehaviour
{
private int score;
public TextMeshPro TMP;
void Start()
{
TMP = GetComponent<TextMeshPro>();
score = 0;
}
void Update()
{
TMP.text = score.ToString();
score++;
}
}
The text is not changing, and I dont know why. The error in the console is "NullReferenceException: Object reference not set to an instance of an object
Num.Update () (at Assets/Scripts/Num.cs:19)"
The error is that your script isn't finding a TextMeshPro sibling component. If you're using the UI version, what you actually want is to find a TextMeshProUGUI
I'm guessing it's a text ui from what you said. If it is a text UI and Textmeshpro, then use TMPro.TextMeshProUGUI varName;

How can I link my C# scripts so that item count influences score in my Unity game?

I am trying to make it so that collecting an item will cause the score to increase. After perusing the documentation for Unity, I have written the following C# scripts. CollectableItem.cs is attached to the items in the game. ScoreBoard.cs is attached to the UI display. I'm getting the error message, "'ScoreBoard.score' is inaccessible due to its protection level." If I make the variables in ScoreBoard.cs public, I get a different error message: "An object reference is required for the non-static field, method, or property 'ScoreBoard.score'."
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollectibleItem : MonoBehaviour {
[SerializeField] private string itemName;
[SerializeField] private int pointsValue;
void OnTriggerEnter(Collider other) {
Managers.Inventory.AddItem(itemName);
Destroy(this.gameObject);
ScoreBoard.score += pointsValue;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreBoard : MonoBehaviour {
[SerializeField] private Text scoreLabel;
private int score;
void Start () {
score = 0;
}
void Update () {
scoreLabel.text = "Score: " + score.ToString();
}
}
UPDATE: Here is Take 2 on CollectibleItem.cs. Now I'm being informed that "board" does not exist in the current context...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollectibleItem : MonoBehaviour {
[SerializeField] private string itemName;
[SerializeField] private int pointsValue;
void Start() {
var uiObject = GameObject.Find("Timer");
ScoreBoard board = uiObject.GetComponent<ScoreBoard>();
}
void OnTriggerEnter(Collider other) {
Managers.Inventory.AddItem(itemName);
Destroy(this.gameObject);
board.score += pointsValue;
}
}
This is not able to work because you make a so-called static access to the ScoreBoard class. That means you try to change the variable of the ScoreBoard class. What you want to do is to change the variable on one of the instances. When the UI Object is created, an instance of the class of your ScoreBoard-Script is created. Like every item has its own instance of CollectibleItem.
You can get the instance in this way:
var uiObject = GameObject.Find("Name of UI Object");
ScoreBoard board = uiObject.GetComponent<ScoreBoard>();
You can do this in Start() and save the ScoreBoard variable in the script where your other private variables reside and use it later in the trigger, or you can do this directly in your Trigger function and directly set the score:
board.score += pointsValue;
EDIT: You have to place the declaration of Scoreboard inside the class:
ScoreBoard board;
void Start ()
...
Or put the code from start to OnTriggerEnter.

Change GameObject Component on InitializeOnLoad

I created script that i want to use as main script when my game launch. Now i want to access specific button text via that script and change it's text. I have problem because my text is not changing. Here is what i was trying:
static main()
{
Debug.Log("Up and running");
GameObject devButtonText = GameObject.Find("devButtonText");
Text text = devButtonText.GetComponent<Text>();
text.text = "Test";
}
Button is devButton and text is devButtonText
full script
using UnityEngine;
using UnityEditor;
using System.Collections;
using UnityEngine.UI;
[InitializeOnLoad]
public class main : MonoBehaviour {
static main()
{
Debug.Log("Up and running");
GameObject devButton = GameObject.Find("devButton");
Text text = devButton.GetComponentInChildren<Text>();
text.text = "Test";
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
I created script that i want to use as main script when my game launch.
The InitializeOnLoad attribute must be used to run a function when the Unity Editor starts, not the game. Every editor script won't run when you compile your game. Unity documentation
Sometimes, it is useful to be able to run some editor script code in a project as soon as Unity launches without requiring action from the user.
Instead, create an Empty GameObject and attach the following script :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ChangeText : MonoBehaviour
{
private void Awake()
{
GameObject devButton = GameObject.Find("devButton");
Text text = devButton.GetComponentInChildren<Text>();
text.text = "Test";
}
}
Even better :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ChangeText : MonoBehaviour
{
// Drag & Drop the desired Text component here
public Text TextToChange ;
// Write the new content of the Text component
public string NewText ;
private void Awake()
{
TextToChange.text = NewText;
}
}
The script will automatically be called when the scene starts.
When Initializing a MonoBehaviour
You should use Start, Awake or OnEnable.
You shouldn't use constructor, static constructor or field initialization (like public GameObject go = GameObject.Find("devButton");)
This should work:
using UnityEngine;
using UnityEditor;
using System.Collections;
using UnityEngine.UI;
public class main : MonoBehaviour {
void Awake () {
Debug.Log("Up and running");
GameObject devButton = GameObject.Find("devButton");
Text text = devButton.GetComponentInChildren<Text>();
text.text = "Test";
}
}
Edit
Given the name main I guess this is the starting point of your project so if your script is not attached to any game object then Start, Awake or OnEnable would not be called. In this case you should attach it to a game object and change the unity script execution order and bring the script to the earliest point.

Categories