0
\$\begingroup\$

I have created UI text object

enter image description here

And then created Text field in behavior class:

using UnityEngine.UI;

public class Explorer : MonoBehaviour
{
    public Material mat;
    public Text text;

...

void FixedUpdate () {
    ...
    text.text = string.Format("x {0}", scale);

If I just run it, it says

Object reference not set to an instance of an object

at runtime.

If I try to drag ZoomText to Text slot, it doesn't allow me:

enter image description here

If I first drag ZoomText from Hierarchy to Project

enter image description here

then it allows me to set Text slot, but still gives

Object reference not set to an instance of an object

at runtime.

If I am trying to set text field by Find

private void Start()
{
    text = (Text) GameObject.Find("ZoomText");
}

it gives me

Cannot convert type 'UnityEngine.GameObject' to 'UnityEngine.UI.Text'

What I am doing wrong? Suspect may be incorrect types, but how to know correct ones?


enter image description here

\$\endgroup\$
6
  • \$\begingroup\$ Could you show the full ZoomText in the inspector? \$\endgroup\$
    – Zibelas
    Oct 10 '20 at 13:43
  • 1
    \$\begingroup\$ In your Explorer class, you can take a GameObject instead of a Text, than in your Start/Awake, just call a GetComponent<WhateverYourTypeIs>() on it. \$\endgroup\$ Oct 10 '20 at 16:35
  • \$\begingroup\$ @Zibelas see my update pls \$\endgroup\$
    – Dims
    Oct 10 '20 at 18:32
  • \$\begingroup\$ @formatc2013 this worked, but why so complex? why was I able to set material directly? \$\endgroup\$
    – Dims
    Oct 10 '20 at 18:38
  • 3
    \$\begingroup\$ An object in your project folder cannot reference an object in your scene - because scenes can come and go from memory, so you have no guarantee that scene object even exists when you want to read it. Object in the scene can reference each other, or objects in the project folder, but not the other way around. \$\endgroup\$
    – DMGregory
    Oct 10 '20 at 19:07

You must log in to answer this question.

Browse other questions tagged .