- Home /
What is "variable not assigned"?
public class BlobCollection : MonoBehaviour {
public GUIText scoreText;
private int score;
void Start() {
score = 0;
UpdateScore();
}
//Tells game to add to score if player touches blob.
void OnTriggerEnter2D (Collider2D other) {
if (other.gameObject.tag == "Player") {
Destroy(gameObject);
AddScore();
}
}
//Tells score GUI to add to previous score value and then update the display to display the new score.
public void AddScore() {
score ++;
UpdateScore();
}
//Specifies what the GUI text is to display in game.
void UpdateScore() {
scoreText.text = "Blobs Saved: " + score;
}
}
In this code, I am trying to get the score to update each time a blob is touched by the player. However, when it runs and player touches a blob, an appears that states "The variable scoreText of 'BlobCollection' has not been assigned," and the score remains at 0. What can I do to resolve this?
Answer by Andres-Fernandez · Oct 07, 2014 at 06:53 AM
You need to link the scoreText in your script to your GUIText in the scene. Drag the GUIText object from the hierarchy to the blob script scoreText public variable.
This is the correct fix.
You can also use GameObject.Find to assign the variable via script.
Answer by tanuj0092 · Oct 07, 2014 at 06:38 AM
Can you please provide more information?
On which gameobject this script is attached? In this case I guess you must be attaching it to the blob.
In this script, the scoreText is not been assigned as script doesn't know which object is scoreText. Are you publically refering the scoreText through inspector?
Try using adding this line
scoreText = GameObject.Find( "Your GUIText object name" ).GetComponent();
in the start function of your script. (Make sure your GUIText object is active in the hierarchy)
Hi, tanuj. So, I used a sugestion to change all "+ score" to "+ score.ToString()". The error is no longer there, but the score just does not update. It is as if UpdateScore() is never called in the AddScore() method, only the destroy.object part.
Answer by blenderblender · Oct 07, 2014 at 01:38 PM
public class BlobCollection : MonoBehaviour {
public GUIText scoreText;
private int score;
void Start() {
score = 0; UpdateScore();
}
void OnTriggerEnter2D (Collider2D other)
{ if (other.CompareTag( "Player"))
{ Destroy(gameObject);
score++; }
}
//Tells score GUI to add to previous score value and then update the display to display the new score.
void OnGUI() {
GUI.Lable("new Rect (20,20,60,20) , "Blobs Saved: " + score.toString()); }
} }
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Using a script as a member variable in another script. 2 Answers
Editing a variable from another script on collision 3 Answers