Unity says Variable is Unassigned when I assigned it


7808583--987354--upload_2022-1-14_21-14-32.png

As you can see I assigned Canvas1 with canvas but Unity says it is unassigned. Please explain.

7808583--987351--upload_2022-1-14_21-11-12.png

[quote=“cloa513”, post:1, topic: 868238]
Please explain.
[/quote]

Nobody here can explain. We can suggest things for you to look at.

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

  • drag it in using the inspector
  • code inside this script initializes it
  • some OTHER external code initializes it
  • ? something else?

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

https://discussions.unity.com/t/840647/7

You must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

1 Like

are you trying to access the canvas component or the canvas game object?

1 Like

[quote=“altepTest”, post:3, topic: 868238]
are you trying to access the canvas component or the canvas game object?
[/quote]
Thank you for your reply do you mean a canvas module. No I not trying to access a canvas module. It is the canvas game object (the one you might call the main canvas) - the one often listed on the side near the Main Camera and I am trying to instantiate onto it.
[quote=“Kurt-Dekker”, post:2, topic: 868238]
Nobody here can explain. We can suggest things for you to look at.

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

  • drag it in using the inspector
  • code inside this script initializes it
  • some OTHER external code initializes it
  • ? something else?

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

https://discussions.unity.com/t/840647/7

You must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3
[/quote]
Not null because it is listed in the Inspector as you can see.

Unity doesn't lie about null reference exceptions. If it's saying something is null, it's null. You haven't shown the code in question, so you're going to need to post it if we're going to be able to help you.

1 Like
sing System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CreateButtons : MonoBehaviour
{  [SerializeField] private Button1 ts;
    private Button1 a;
    public Canvas canvas1;
    public Values value1;
    private float _px;

    private float _py;

    private string _rowcol;
//    private int _tempnum;
    private int _num;

    private int _row;

    private int _col;

    private int _squ;
    // Start is called before the first frame update
    void Start()
    {
        for (var i = 0; i < value1.col*3; i++) //value1.row is number of rows starting value 9
        {

            for (var j = 0; j < value1.row*3; j++) //value1.row is number of columns starting value 9
            {_py = ((value1.yst + value1.ys * (i)));
                _px = (value1.xst + value1.xs * j);



                            a=Instantiate(ts,new Vector3(_px,_py),Quaternion.identity);
                            a.transform.SetParent (canvas1.transform,false);
                            ;
            }


        }
    }

Can't Unity Inspector permit something that is not allowed by the Unity Game Engine?

is easy to miss if you are not familiar with the editor interface

in your first screenshot the object assigned in the Canvas1 slot is of type Canvas not GameObject. It doesn't have the gameobject icon but the canvas icon.

the code you posted confirms this as your variable is of type canvas not gameobject

The reason you didn't got any errors when you have dragged the game object from scene to the variable slot is that if you create a variable that is of type of a game object component (transform, collider, mesh all of these types) and you drag a game object to the variable slot, unity will assign to the slot the component of that type that is present on the game object.

You can drag the component directly to the slot, in your case the canvas component, will work the same. for convenience unity will let you drag the entire object also. Is a shortcut.

in your code change the Canvas1 to be of type GameObject then drag the Canvas1 game object to the slot again.

Pay attention to the icons.

You can learn more about various types of components and objects in unity in the script reference

https://docs.unity3d.com/ScriptReference/Canvas.html

Uh, it really doesn't make a difference if you assign a reference to a game object or a component, as components all have a .gameObject and .transform property.

I don't think there's anything wrong with the code and how the fields are reference. I tested some similar code below which all worked as expected:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CreateButtons : MonoBehaviour
{
    [SerializeField]
    private Button buttonPrefab;

    [SerializeField]
    private Canvas canvasParent;

    [SerializeField]
    private int buttonSpawnAmount = 10;

    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < buttonSpawnAmount; i++)
        {
            Button spawnButton = Instantiate(buttonPrefab, Vector3.zero, Quaternion.identity);
            spawnButton.transform.SetParent(canvasParent.transform, false);
        }
    }
}

I'm starting to suspect OP has another instance of the component with unassigned references somewhere in the project.

[quote=“cloa513”, post:4, topic: 868238]
Not null because it is listed in the Inspector as you can see.
[/quote]

The one you’re looking at… WHEN you’re looking at it.

How about other ones (do you have others that you accidentally dragged on?) and what about WHEN… not everything happens in the order you think it does. See my post on using Debug.Log() to learn more.

EXACTLY what Spiney says. Something is null. Might not be the thing you are insisting ISN’T null, but that’s up to you to determine using the steps listed above.

It is not a Null object- it is an unassigned statement- the latter is an Unity statement not runtime statement.

By the way, my inspector won't allow by the drop down menu to add Game Objects- only assets- I assigned the canvas to canvas1 by drag and drop . Is that a bug?

[quote=“cloa513”, post:11, topic: 868238]
By the way, my inspector won’t allow by the drop down menu to add Game Objects- only assets- I assigned the canvas to canvas1 by drag and drop . Is that a bug?
[/quote]
No there should be two tabs up the top for an asset or scene object:
7812507--988113--upload_2022-1-16_13-33-1.png

1 Like

Thank you. I am not completely sure if it was there before but it is definitely is there now and now that variable doesn't bug.

So you were adding an asset level reference before? That would definitely cause an error I would think.


No I dragged the icon from the Game Object area. As you can see Inspector accepts it but doesn't recognize it.

I has a similar error right now and the reason was that I had my script on another gameobject that I created by copy/paste the original one. So can you make sure, that there are no other script of the type CreateButtons on any other gameobject? Maybe on the canvas object for example.