Null Refrence Expection
I am pretty new to unity
I am trying to change the value of text object in the canvas on update to do this I attached a script called textEdit to my text object but it attached itself to the main camera also and throws and nullRefrenceExpection error pointing at the camera what am I doing wrong here.
my textEdit Script looks like this
using UnityEngine; using UnityEngine.UI; using System.Collections;
public class textEdit : MonoBehaviour {
public static int score;
Text text;
void awake()
{
text = GetComponent<Text>();
score = 0;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
text = GetComponent<Text>();
text.text = "test";
}
}
As a side note: You probably don't want to update your text every frame (That's roughly 60 times per second). I'm guessing you want to display your score right? So ins$$anonymous$$d make the score variable non-static and make a non-static AddScore function ins$$anonymous$$d that increments your score variable and updates the text at the same time, and is called whenever the condition to gain points is met.
Statics shouldn't be used on in-game object instances, statics are used when there's only one instance of this variable, function or class.
This totally makes sense. Thanks @vyra but for now I need it to print on update on every frame as I am trying to capture some input from a bluetooth screen port and print the value to screen
Answer by JedBeryll · Oct 01, 2016 at 07:06 AM
There is probably no Text component in the camera.
void Update () {
if (text != null) {
text.text = "test";
}
}
But lots of other problems. This person needs to work through simpler examples and more basics.
awake is misspelled. text is needlessly cached AND looked-up every frame. Why aren't they able to remove the script from the camera? static score ... ugg.
Answer by adi5402 · Oct 02, 2016 at 12:40 PM
Thanks @Owen-Reynolds for you input . I am actually trying to learn how to capture serial bluetooth input so I want to print the value coming from the com ports to the screen while the game runs so I can then trigger and event based on the data I am getting. The bluetooth device I am trying to connect to you sends the speed of a car or cycle based on wheel rotation per second.
for now I was just trying to find a way to print to screen on update.
Your answer
![](https://koobas.hobune.stream/wayback/20220612093743im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
C # script taking values from one object and modifying another. 0 Answers
click on object then zoom in 0 Answers
changing player position after scene load 0 Answers
Trigger Script not working 1 Answer