Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This question was closed Feb 13, 2020 at 08:26 PM by ZachRoman121 for the following reason:

Other

avatar image
-1
Question by ZachRoman121 · Feb 28, 2017 at 01:30 PM · uierrortextitemsstacking

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)
 

Comment
Add comment · Show 7
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image HarshadK · Feb 28, 2017 at 02:06 PM 0
Share

What error are you getting?

avatar image ZachRoman121 HarshadK · Feb 28, 2017 at 02:20 PM 0
Share

@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

avatar image Hellium · Feb 28, 2017 at 02:25 PM 0
Share

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

avatar image ZachRoman121 Hellium · Mar 01, 2017 at 02:07 AM 0
Share

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

avatar image MarshallN · Feb 28, 2017 at 03:05 PM 0
Share

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.

avatar image ZachRoman121 MarshallN · Mar 01, 2017 at 01:34 AM 0
Share

They are children of a canvas

avatar image ZachRoman121 · Mar 01, 2017 at 12:10 PM 0
Share

Ugh. I have still found no fix. Is there another way to add text to a canvas?

1 Reply

  • Sort: 
avatar image
0
Best Answer

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Follow this Question

Answers Answers and Comments

118 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges