- Home /
Other
Error when adding a UI Text component to a gameobject?
Hi! I am making a stacking system so the player can stack items. But. When i add a UI Text component to show how many items are on that stack. I get an error. Here's my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class inventoryScript : MonoBehaviour {
GameObject[] slotContentsGo = new GameObject[inventorySlotsCount];
public static int inventorySlotsCount = 52;
public static Items[] slotContents = new Items[inventorySlotsCount];
public GameObject[] inventorySlotsAr = new GameObject[inventorySlotsCount];
void Start() {
getSlots ();
}
static void hideInventory() {
GameObject inventory = GameObject.Find ("Inventory");
for (int i = 0; i < inventory.transform.childCount; i++) {
inventory.transform.GetChild (i).gameObject.SetActive (!inventory.transform.GetChild (i).gameObject.activeInHierarchy);
}
}
public void takeItem(Items itemToTake) {
for (int i = 0; i < slotContents.Length; i++) {
if (itemToTake == slotContents [i] && itemToTake != null) {
slotContents [i] = null;
Destroy (slotContentsGo[i]);
break;
}
}
}
public void clearInventory() {
for (int i = 0; i < inventorySlotsCount; i++) {
slotContents [i] = null;
Destroy (slotContentsGo [i]);
}
}
public void removeAtSlot(int slot) {
for (int i = 0; i < slotContents.Length; i++) {
if (i == slot) {
if (slotContents [slot] != null) {
slotContents [i] = null;
Destroy (slotContentsGo [i]);
}
}
}
}
public void addItem(Items itemToAdd) {
for (int i = 0; i < slotContents.Length; i++) {
if (slotContents [i] == null && itemToAdd != null && itemToAdd.stackable == false) {
slotContents [i] = itemToAdd;
GameObject returnedItem = createItem (itemToAdd.itemSprite, inventorySlotsAr [i].gameObject.transform, itemToAdd.itemName);
slotContentsGo [i] = returnedItem;
break;
}
}
}
// Relevant bit
public GameObject createItem(Sprite imageSprite, Transform slot, string itemName) {
// Here i am creating two gameobjects. The item. And the stack text
// But i get an error when i try to add the Text component
GameObject createObj = new GameObject ();
GameObject stackText = new GameObject (itemName + " StackText");
createObj.AddComponent<Image> ();
createObj.GetComponent<Image> ().sprite = imageSprite;
createObj.transform.position = slot.position;
createObj.transform.rotation = slot.rotation;
createObj.transform.SetParent (slot.transform);
createObj.transform.localScale = new Vector3 (slot.transform.localScale.x, slot.transform.localScale.y);
createObj.name = itemName;
stackText.transform.SetParent (createObj.transform);
stackText.AddComponent<RectTransform> ();
stackText.transform.position = new Vector3 (slot.transform.position.x, slot.transform.position.y);
stackText.transform.localScale = new Vector3 (slot.transform.localScale.x, slot.transform.localScale.y);
stackText.AddComponent<Text> ();
stackText.GetComponent<Text> ().fontSize = 45;
stackText.GetComponent<Text> ().fontStyle = FontStyle.Bold;
stackText.GetComponent<Text> ().alignment = TextAnchor.LowerLeft;
stackText.GetComponent<Text> ().color = new Color (0, 0, 0, 255);
return createObj;
}
void getSlots() {
for (int i = 0; i < inventorySlotsCount; i++) {
if (inventorySlotsAr [i] == null) {
inventorySlotsAr [i] = GameObject.Find ("inventorySlot (" + i.ToString() + ")");
}
if(i == 0) {
inventorySlotsAr [i] = GameObject.Find ("inventorySlot");
}
}
}
}
Edit: This is my error
NullReferenceException
UnityEngine.TextGenerator.Populate_Internal_cpp (System.String str, UnityEngine.Font font, Color color, Int32 fontSize, Single scaleFactor, Single lineSpacing, FontStyle style, Boolean richText, Boolean resizeTextForBestFit, Int32 resizeTextMinSize, Int32 resizeTextMaxSize, Int32 verticalOverFlow, Int32 horizontalOverflow, Boolean updateBounds, TextAnchor anchor, Single extentsX, Single extentsY, Single pivotX, Single pivotY, Boolean generateOutOfBounds, Boolean alignByGeometry, System.UInt32& error) (at C:/buildslave/unity/build/artifacts/generated/common/modules/TextRendering/TextRenderingBindings.gen.cs:690)
UnityEngine.TextGenerator.Populate_Internal (System.String str, UnityEngine.Font font, Color color, Int32 fontSize, Single scaleFactor, Single lineSpacing, FontStyle style, Boolean richText, Boolean resizeTextForBestFit, Int32 resizeTextMinSize, Int32 resizeTextMaxSize, VerticalWrapMode verticalOverFlow, HorizontalWrapMode horizontalOverflow, Boolean updateBounds, TextAnchor anchor, Vector2 extents, Vector2 pivot, Boolean generateOutOfBounds, Boolean alignByGeometry, UnityEngine.TextGenerationError& error) (at C:/buildslave/unity/build/artifacts/generated/common/modules/TextRendering/TextRenderingBindings.gen.cs:671)
UnityEngine.TextGenerator.PopulateAlways (System.String str, TextGenerationSettings settings) (at C:/buildslave/unity/build/Runtime/TextRendering/Managed/TextGenerator.cs:265)
UnityEngine.TextGenerator.PopulateWithError (System.String str, TextGenerationSettings settings) (at C:/buildslave/unity/build/Runtime/TextRendering/Managed/TextGenerator.cs:249)
UnityEngine.TextGenerator.Populate (System.String str, TextGenerationSettings settings) (at C:/buildslave/unity/build/Runtime/TextRendering/Managed/TextGenerator.cs:240)
UnityEngine.TextGenerator.GetPreferredHeight (System.String str, TextGenerationSettings settings) (at C:/buildslave/unity/build/Runtime/TextRendering/Managed/TextGenerator.cs:220)
UnityEngine.UI.Text.get_preferredHeight () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Text.cs:522)
UnityEditor.Events.LayoutPropertiesPreview.<OnPreviewGUI>m__3 (ILayoutElement e) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEditor.UI/UI/LayoutPropertiesPreview.cs:97)
UnityEngine.UI.LayoutUtility.GetLayoutProperty (UnityEngine.RectTransform rect, System.Func`2 property, Single defaultValue, ILayoutElement& source) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Layout/LayoutUtility.cs:86)
UnityEditor.Events.LayoutPropertiesPreview.OnPreviewGUI (Rect r, UnityEngine.GUIStyle background) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEditor.UI/UI/LayoutPropertiesPreview.cs:97)
UnityEditor.ObjectPreview.OnInteractivePreviewGUI (Rect r, UnityEngine.GUIStyle background) (at C:/buildslave/unity/build/Editor/Mono/Inspector/Editor.cs:113)
UnityEditor.ObjectPreview.DrawPreview (IPreviewable defaultPreview, Rect previewArea, UnityEngine.Object[] targets) (at C:/buildslave/unity/build/Editor/Mono/Inspector/Editor.cs:225)
UnityEditor.ObjectPreview.DrawPreview (Rect previewArea) (at C:/buildslave/unity/build/Editor/Mono/Inspector/Editor.cs:128)
UnityEditor.InspectorWindow.DrawPreviewAndLabels () (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:765)
UnityEditor.InspectorWindow.OnGUI () (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:392)
System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:222)
@Harshad$$anonymous$$ I am getting a Null Reference Exeption. A very long one. And the problem seems to be when i add the text component
A NullReferenceException
can't be thrown when adding a component in your case since stackText
is used many times before. Please, copy-paste the exact error below the code with the exact line throwing the exception
The thing is. When i double click on the error. It opens some kind of weird inspecter in unity The inspecter shows a child drop-down that when clicked. Allows you to enter the size. Then. There is a "Position" thing aswell. It shows a position. Showing a X H Y W Coords. And there is a $$anonymous$$ and max size. there is also a "Panes" dropdown aswell
If your inventorySlots aren't children of the Canvas, it might cause this behaviour. UI Text can only be added to objects on the Canvas.
Ugh. I have still found no fix. Is there another way to add text to a canvas?
Answer by HarshadK · Mar 01, 2017 at 12:41 PM
If you look at the stack trace above, the method UnityEngine.TextGenerator.Populate_Internal_cpp
takes an argument called font
which is of type UnityEngine.Font
. So when you try to add the Text component the font field is going to be initialized to null, which in turn is causing you the null reference exception.
One way to overcome this is to create a prefab of the gameobject with Text component added to it and instantiate a gameobject from this prefab and set the required values on this instantiated prefab.
Follow this Question
Related Questions
There is no 'CanvasRenderer' attached to the " Caret" game object 2 Answers
My script won't let me change the text of a UI object 4 Answers
How to get the width of UI Text with Horizontal Overflow? 4 Answers
How to change color of animated Text component 2 Answers
Content size fitter does not update rect transform immediately 1 Answer