Object reference not set to an instance of an object как исправить юнити

A NullReferenceException happens when you try to access a reference variable that isn’t referencing any object. If a reference variable isn’t referencing an object, then it’ll be treated as null. The run-time will tell you that you are trying to access an object, when the variable is null by issuing a NullReferenceException.

Reference variables in c# and JavaScript are similar in concept to pointers in C and C++. Reference types default to null to indicate that they are not referencing any object. Hence, if you try and access the object that is being referenced and there isn’t one, you will get a NullReferenceException.

When you get a NullReferenceException in your code it means that you have forgotten to set a variable before using it. The error message will look something like:

NullReferenceException: Object reference not set to an instance of an object
  at Example.Start () [0x0000b] in /Unity/projects/nre/Assets/Example.cs:10 

This error message says that a NullReferenceException happened on line 10 of the script file Example.cs. Also, the message says that the exception happened inside the Start() function. This makes the Null Reference Exception easy to find and fix. In this example, the code is:

//c# example
using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

    // Use this for initialization
    void Start () {
        __GameObject__The fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject's functionality is defined by the Components attached to it. [More info](class-GameObject.html)<span class="tooltipGlossaryLink">See in [Glossary](Glossary.html#GameObject)</span> go = GameObject.Find("wibble");
        Debug.Log(go.name);
    }

}

The code simply looks for a game object called “wibble”. In this example there is no game object with that name, so the Find() function returns null. On the next line (line 9) we use the go variable and try and print out the name of the game object it references. Because we are accessing a game object that doesn’t exist the run-time gives us a NullReferenceException

Null Checks

Although it can be frustrating when this happens it just means the script needs to be more careful. The solution in this simple example is to change the code like this:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

    void Start () {
        GameObject go = GameObject.Find("wibble");
        if (go) {
            Debug.Log(go.name);
        } else {
            Debug.Log("No game object called wibble found");
        }
    }

}

Now, before we try and do anything with the go variable, we check to see that it is not null. If it is null, then we display a message.

Try/Catch Blocks

Another cause for NullReferenceException is to use a variable that should be initialised in the InspectorA Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary
. If you forget to do this, then the variable will be null. A different way to deal with NullReferenceException is to use try/catch block. For example, this code:

using UnityEngine;
using System;
using System.Collections;

public class Example2 : MonoBehaviour {

    public Light myLight; // set in the inspector

    void Start () {
        try {
            myLight.color = Color.yellow;
        }       
        catch (NullReferenceException ex) {
            Debug.Log("myLight was not set in the inspector");
        }
    }

}

In this code example, the variable called myLight is a Light which should be set in the Inspector window. If this variable is not set, then it will default to null. Attempting to change the color of the light in the try block causes a NullReferenceException which is picked up by the catch block. The catch block displays a message which might be more helpful to artists and game designers, and reminds them to set the light in the inspector.

Summary

  • NullReferenceException happens when your script code tries to use a variable which isn’t set (referencing) and object.
  • The error message that appears tells you a great deal about where in the code the problem happens.
  • NullReferenceException can be avoided by writing code that checks for null before accessing an object, or uses try/catch blocks.

Value type vs Reference type

In many programming languages, variables have what is called a “data type”. The two primary data types are value types (int, float, bool, char, struct, …) and reference type (instance of classes). While value types contains the value itself, references contains a memory address pointing to a portion of memory allocated to contain a set of values (similar to C/C++).

For example, Vector3 is a value type (a struct containing the coordinates and some functions) while components attached to your GameObject (including your custom scripts inheriting from MonoBehaviour) are reference type.

When can I have a NullReferenceException?

NullReferenceException are thrown when you try to access a reference variable that isn’t referencing any object, hence it is null (memory address is pointing to 0).

Some common places a NullReferenceException will be raised:

Manipulating a GameObject / Component that has not been specified in the inspector

// t is a reference to a Transform.
public Transform t ;

private void Awake()
{
     // If you do not assign something to t
     // (either from the Inspector or using GetComponent), t is null!
     t.Translate();
}

Retrieving a component that isn’t attached to the GameObject and then, trying to manipulate it:

private void Awake ()
{
    // Here, you try to get the Collider component attached to your gameobject
    Collider collider = gameObject.GetComponent<Collider>();

    // But, if you haven't any collider attached to your gameobject,
    // GetComponent won't find it and will return null, and you will get the exception.
    collider.enabled = false ;
}

Accessing a GameObject that doesn’t exist:

private void Start()
{
    // Here, you try to get a gameobject in your scene
    GameObject myGameObject = GameObject.Find("AGameObjectThatDoesntExist");

    // If no object with the EXACT name "AGameObjectThatDoesntExist" exist in your scene,
    // GameObject.Find will return null, and you will get the exception.
    myGameObject.name = "NullReferenceException";
}

Note: Be carefull, GameObject.Find, GameObject.FindWithTag, GameObject.FindObjectOfType only return gameObjects that are enabled in the hierarchy when the function is called.

Trying to use the result of a getter that’s returning null:

var fov = Camera.main.fieldOfView;
// main is null if no enabled cameras in the scene have the "MainCamera" tag.

var selection = EventSystem.current.firstSelectedGameObject;
// current is null if there's no active EventSystem in the scene.

var target = RenderTexture.active.width;
// active is null if the game is currently rendering straight to the window, not to a texture.

Accessing an element of a non-initialized array

private GameObject[] myObjects ; // Uninitialized array

private void Start()
{
    for( int i = 0 ; i < myObjects.Length ; ++i )
        Debug.Log( myObjects[i].name ) ;
}

Less common, but annoying if you don’t know it about C# delegates:

delegate double MathAction(double num);

// Regular method that matches signature:
static double Double(double input)
{
    return input * 2;
}

private void Awake()
{
    MathAction ma ;

    // Because you haven't "assigned" any method to the delegate,
    // you will have a NullReferenceException
    ma(1) ;

    ma = Double ;

    // Here, the delegate "contains" the Double method and
    // won't throw an exception
    ma(1) ;
}

How to fix ?

If you have understood the previous paragraphes, you know how to fix the error: make sure your variable is referencing (pointing to) an instance of a class (or containing at least one function for delegates).

Easier said than done? Yes, indeed. Here are some tips to avoid and identify the problem.

The “dirty” way : The try & catch method :

Collider collider = gameObject.GetComponent<Collider>();

try
{
    collider.enabled = false ;
}       
catch (System.NullReferenceException exception) {
    Debug.LogError("Oops, there is no collider attached", this) ;
}

The “cleaner” way (IMHO) : The check

Collider collider = gameObject.GetComponent<Collider>();

if(collider != null)
{
    // You can safely manipulate the collider here
    collider.enabled = false;
}    
else
{
    Debug.LogError("Oops, there is no collider attached", this) ;
}

When facing an error you can’t solve, it’s always a good idea to find the cause of the problem. If you are “lazy” (or if the problem can be solved easily), use Debug.Log to show on the console information which will help you identify what could cause the problem. A more complex way is to use the Breakpoints and the Debugger of your IDE.

Using Debug.Log is quite useful to determine which function is called first for example. Especially if you have a function responsible for initializing fields. But don’t forget to remove those Debug.Log to avoid cluttering your console (and for performance reasons).

Another advice, don’t hesitate to “cut” your function calls and add Debug.Log to make some checks.

Instead of :

 GameObject.Find("MyObject").GetComponent<MySuperComponent>().value = "foo" ;

Do this to check if every references are set :

GameObject myObject = GameObject.Find("MyObject") ;

Debug.Log( myObject ) ;

MySuperComponent superComponent = myObject.GetComponent<MySuperComponent>() ;

Debug.Log( superComponent ) ;

superComponent.value = "foo" ;

Even better :

GameObject myObject = GameObject.Find("MyObject") ;

if( myObject != null )
{
   MySuperComponent superComponent = myObject.GetComponent<MySuperComponent>() ;
   if( superComponent != null )
   {
       superComponent.value = "foo" ;
   }
   else
   {
        Debug.Log("No SuperComponent found onMyObject!");
   }
}
else
{
   Debug.Log("Can't find MyObject!", this ) ;
}

Sources:

  1. http://answers.unity3d.com/questions/47830/what-is-a-null-reference-exception-in-unity.html
  2. https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it/218510#218510
  3. https://support.unity3d.com/hc/en-us/articles/206369473-NullReferenceException
  4. https://unity3d.com/fr/learn/tutorials/topics/scripting/data-types

NullReferenceException возникает, когда вы пытаетесь получить доступ к ссылочной переменной, которая не ссылается на какой-либо объект. Если ссылочная переменная не ссылается на объект, она будет рассматриваться как null. Время выполнения сообщит вам, что вы пытаетесь получить доступ к объекту, когда переменная имеет значение null, создав исключение NullReferenceException.

Ссылочные переменные в C# и JavaScript по своей концепции аналогичны указателям в C и C++. Типы ссылок по умолчанию имеют значение null, чтобы указать, что они не ссылаются на какой-либо объект. Следовательно, если вы попытаетесь получить доступ к объекту, на который ссылаются, а его нет, вы получите NullReferenceException.

Когда вы получаете NullReferenceException в своем коде, это означает, что вы забыли установить переменную перед ее использованием. Сообщение об ошибке будет выглядеть примерно так:

NullReferenceException: Object reference not set to an instance of an object
at Example.Start () [0x0000b] in /Unity/projects/nre/Assets/Example.cs:10

В этом сообщении об ошибке говорится, что NullReferenceException произошло в строке 10 файла сценария Example.cs. Кроме того, в сообщении говорится, что исключение произошло внутри функции Start(). Это упрощает поиск и исправление исключения нулевой ссылки. В этом примере код такой:

//c# example
using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

// Use this for initialization
void Start () {
__GameObject__The fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject's functionality is defined by the Components attached to it. [More info](class-GameObject)See in [Glossary](Glossary#GameObject) go = GameObject.Find("wibble");
Debug.Log(go.name);
}

}

Код просто ищет игровой объект под названием “wibble”. В этом примере нет игрового объекта с таким именем, поэтому функция Find() возвращает null. В следующей строке (строка 9) мы используем переменную go и пытаемся вывести имя игрового объекта, на который она ссылается. Поскольку мы обращаемся к несуществующему игровому объекту, среда выполнения выдает нам NullReferenceException

Нулевые проверки

Хотя это может расстраивать, когда это происходит, это просто означает, что сценарий должен быть более осторожным. Решение в этом простом примере состоит в том, чтобы изменить код следующим образом:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

void Start () {
GameObject go = GameObject.Find("wibble");
if (go) {
Debug.Log(go.name);
} else {
Debug.Log("No game object called wibble found");
}
}

}

Теперь, прежде чем пытаться что-то делать с переменной go, мы проверяем, не является ли она null. Если это null, мы показываем сообщение.

Попробовать/перехватить блоки

Другой причиной NullReferenceException является использование переменной, которая должна быть инициализирована в ИнспектореОкно Unity, в котором отображается информация о текущем выбранном игровом объекте, активе или настройках проекта, что позволяет просматривать и редактировать значения. Дополнительная информация
См. в Словарь
. Если вы забудете это сделать, переменная будет иметь значение null. Другой способ справиться с NullReferenceException — использовать блок try/catch. Например, этот код:

using UnityEngine;
using System;
using System.Collections;

public class Example2 : MonoBehaviour {

public Light myLight; // set in the inspector

void Start () {
try {
myLight.color = Color.yellow;
}
catch (NullReferenceException ex) {
Debug.Log("myLight was not set in the inspector");
}
}

}

В этом примере кода переменная с именем myLight — это Light, которую следует установить в окне инспектора. Если эта переменная не задана, по умолчанию она будет иметь значение null. Попытка изменить цвет света в блоке try вызывает NullReferenceException, которое подхватывается блоком catch. Блок catch отображает сообщение, которое может быть более полезным для художников и геймдизайнеров, и напоминает им о необходимости установить свет в инспекторе.

Обзор

  • NullReferenceException возникает, когда ваш код скрипта пытается использовать переменную, которая не установлена ​​(ссылка) и объект.
  • Отображаемое сообщение об ошибке многое говорит о том, в каком месте кода возникает проблема.
  • NullReferenceException можно избежать, написав код, который проверяет null перед доступом к объекту или использует блоки try/catch.

Unity выдает ошибку

NullReferenceException: Object reference not set to an instance of an object
ActorController.CharacterMove () (at Assets/Scripts/Actor/ActorController.cs:43)
ActorController.Update () (at Assets/Scripts/Actor/ActorController.cs:32).

указывающую на строку

moveVector.x = mContr.Horizontal() * speedMove;

класса ActorController.

Не понимаю сути ошибки.

public class ActorController : MonoBehaviour {

//Скорость ходьбы
public float speedMove;
//Сила прыжка
public float jumpPower;

//Направление движения персонажа
private Vector3 moveVector;

private CharacterController ch_controller;
private Animator ch_animator;
private ActorMobileController mContr;

// Use this for initialization
void Start () {

    ch_controller = GetComponent<CharacterController>();
    ch_animator = GetComponent<Animator>();
    mContr = GameObject.FindGameObjectWithTag("Joystick").GetComponent<ActorMobileController>();

}

// Update is called once per frame
void Update () {

    GamingGravity();
    CharacterMove();

}

//Метод перемещения персонажа
private void CharacterMove()
{

    if (ch_controller.isGrounded)
    {
        moveVector = Vector3.zero;
        moveVector.x = mContr.Horizontal() * speedMove;
        moveVector.z = mContr.Vertical() * speedMove;
    }

    if (moveVector.x != 0 || moveVector.z != 0) ch_animator.SetBool("Move", true);
    else ch_animator.SetBool("Move", false);

    if (Vector3.Angle(Vector3.forward, moveVector) > 1f || Vector3.Angle(Vector3.forward, moveVector) == 0)
    {

        Vector3 direct = Vector3.RotateTowards(transform.forward, moveVector, speedMove, 0.0f);
        transform.rotation = Quaternion.LookRotation(direct);

    }

    moveVector.y = gravityForce;

    ch_controller.Move(moveVector * Time.deltaTime);
}
}


public class ActorMobileController : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler {

private Image joystickBG;
[SerializeField]
private Image joystick;
private Vector2 inputVector;

// Use this for initialization
void Start()
{

    joystickBG = GetComponent<Image>();
    joystick = transform.GetChild(0).GetComponent<Image>();

}

public virtual void OnPointerDown(PointerEventData ped)
{

    OnDrag(ped);

}

public virtual void OnPointerUp(PointerEventData ped)
{

    inputVector = Vector2.zero;
    joystick.rectTransform.anchoredPosition = Vector2.zero;

}

public virtual void OnDrag(PointerEventData ped)
{

    Vector2 pos;
    if(RectTransformUtility.ScreenPointToLocalPointInRectangle(joystickBG.rectTransform, ped.position, ped.pressEventCamera, out pos))
    {

        pos.x = (pos.x / joystickBG.rectTransform.sizeDelta.x);
        pos.y = (pos.y / joystickBG.rectTransform.sizeDelta.x);

        inputVector = new Vector2(pos.x * 2 - 1, pos.y * 2 - 1);
        inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;

        joystick.rectTransform.anchoredPosition = new Vector2(inputVector.x * (joystickBG.rectTransform.sizeDelta.x / 2), inputVector.y * (joystickBG.rectTransform.sizeDelta.y / 2));

    }
}

public float Horizontal()
{

    if (inputVector.x != 0) return inputVector.x;
    else return Input.GetAxis("Horizontal");

}

public float Vertical()
{

    if (inputVector.y != 0) return inputVector.y;
    else return Input.GetAxis("Vertical");

}

}

MarianD's user avatar

MarianD

14.1k3 золотых знака18 серебряных знаков29 бронзовых знаков

задан 26 фев 2018 в 8:35

Владимир Александров's user avatar

0

Суть ошибки NullReferenceException – вы пытаетесь что-то сделать со ссылочной переменной, которая имеет значение null. т.е. mContr на момент вашего обращения к ней ничего не назначено и эта переменная указывает в пустоту. Как следствие вызов метода у пустоты выдаёт ошибку.

А раз там пусто, значит нижеприведённая строчка кода ничего не находит. Не стоит делать такие длинные цепочки вызовов, когда вы не уверены, что всё и везде назначено. Как вариант, хотя бы, ставьте проверку, чтобы знать сразу, что всё плохо. Например, так:

mContr = GameObject.FindGameObjectWithTag("Joystick").GetComponent<ActorMobileController>();
Debug.Assert(mContr, "Not found ActorMobileController!", this);

ответ дан 26 фев 2018 в 8:43

M. Green's user avatar

M. GreenM. Green

5,1031 золотой знак10 серебряных знаков17 бронзовых знаков

The unity object reference not set to an instance of an object error always happens when developers and programmers access an empty object. As a result, the null reference confuses the system because it does not have anything to hold on to or reach, blocking further operations and code alterations.unity object reference not set to an instance of an object

Fortunately, our profound guide includes several debugging solutions and explains why an invalid bject reference ruins your programming experience. Therefore, nothing will stop you from clearing your document after reading this article and its chapters.

Contents

  • Why Is the Unity Object Reference Not Set to an Instance of an Object Error Occuring?
    • – Developing Games in C# Language
    • – Failing To Include an Instance of a Class
    • – Accessing Elements and Tags With Empty Objects
  • Unity Object Reference Mistake: Quickest Solutions
    • – Writing Nested Collection Initializers
    • – Correct Life Cycles and Empty View Models
  • Conclusion

Why Is the Unity Object Reference Not Set to an Instance of an Object Error Occuring?

The system does not set the unity object reference to an instance of an object when developers and programmers access an empty object in the script. Consequently, the lack of adequate connection confuses the system because it does not have anything to reach for, halting further processes and commands.

In other words, the system specifies a unique function or value in your file that does not exist, which might affect the complete project. For instance, developers reported the same issue when working with C# and creating complex operations using this language’s functions and elements.

As a result, the program will remain functional until the system understands the script, which can be anywhere or of any value. This mistake has several forms and messages that provide clues as to what is wrong with the project and what developers can do to debug the script.

For example, the error usually includes:

  • The invalid file’s location or element.
  • Specifying the lack of complete objects.
  • Objects with fair values.

However, this bug should not demoralize less experienced developers and programmers because the solutions syntaxes are not challenging. But first, we will show the invalid scripts that reproduce the error so that you can learn more about the structure. Therefore, we suggest reading the following chapters because they contain real-life examples that recreate the message.

– Developing Games in C# Language

As explained in the former section, it is common for this mistake to pop up when developers create games in C# language. For instance, a single or more elements in the script can have empty objects, preventing the program from accessing the correct value or location.

The following example shows the code’s first part:

using UnityEngine;

using System.Collections;

public class DeathFieldScript : MonoBehaviour {

// Use this for initialization

void Start () {

}

// Update is called once per frame

void Update () {

}

void OnTriggerEnter (Collider other){

BallController ballController = other.GetComponent<BallController>();

If (ballController){

ballController.Die();

}

}

}

The code provided in this example introduces the field script, which is a critical part of every game. As you can tell, the values and objects appear functional, but the system still launches a mistake. After that, however, the code will only be complete if we introduce the controller script.

You can learn more about this code in the following example:

using UnityEngine;

using System.Collections;

public class BallController : MonoBehaviour {

// Use this for initialization

void Start () {

}

// Update is called once per frame

void Update () {

}

public void Die(){

GameObject paddleGameObject = GameObject.Find(“paddle”);

Destroy(this.gameObject);

PaddleController paddleController = paddleGameObject.GetComponent<PaddleController>();

paddleController.SpawnBall();

}

}

Unfortunately, this is only one instance a developer might experience this mistake. As a result, we will show you a few more complex codes that recreate this error and confuse your program.

– Failing To Include an Instance of a Class

Our experts explain that failing to include an instance of a class in a variable creates the same mistake in your document. So, again, although the script appears perfect to an inexperienced eye, a professional can quickly locate the bug. Next, we will show you a more complex example with many elements to see if you can notice the class without an instance.Unity Object Reference Not Set to an Instance of an Object Causes

The following example does not have an instance of a class:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Birds : MonoBehaviour

{

Vector2 _startPosition;

Rigidbody2D _rigidbody2D;

SpriteRenderer _spriteRenderer;

void awake()

{

_rigidbody2D = GetComponent<rigidbody2d>();

_spriteRenderer = GetComponent<spriterenderer>();

}

// Start is called prior to the first frame update

void Start()

{

_startPosition = _rigidbody2D.position;

_rigidbody2D.isKinematic = true;

}

void OnMouseDown()

{

_spriteRenderer.color = Color.red;

}

void OnMouseUp()

{

var currentPosition = GetComponent<rigidbody2d>().position;

Vector2 direction = _startPosition – currentPosition;

direction.Normalize();

_rigidbody2D.isKinematic = false;

_rigidbody2D.AddForce(direction * 750);

_spriteRenderer.color = Color.white;

}

void OnMouseDrag()

{

Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

transform.position = new Vector3 (mousePosition.x, mousePosition.y, transform.position.z);

}

// Update is called once per frame

void Update()

{

}

}

As you can tell, the tags and elements in this example create a straightforward game in C#, similar to the former code. However, the values are more advanced than before, confirming our claim that no one is safe from this mistake because it can affect beginners and professionals. As a result, we would like to show you a final incorrect example and the complete error message in the following chapter.

– Accessing Elements and Tags With Empty Objects

We explained this mistake usually happens when developers access elements and tags with empty objects in the system. However, what does the code look and how can developers tell the difference? We will provide a real-life example to answer these questions, which are crucial for understanding how to debug your system. Of course, our experts want to note your file will differ, but this should encourage you because the solutions remain the same.

The tags and elements in this example have empty objects:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class PatrolBehaviour : StateMachineBehaviour

{

private GameObject[] patrolPoints;

public float speed;

int randomPoint;

override public void OnStateEnter (Animator animator, AnimatorStateInfo stateInfo, int layerIndex)

{

patrolPoints = GameObject.FindGameObjectsWithTag (“patrolPoints”);

randomPoint = Random.Range (0, patrolPoints.Length);

}

override public void OnStateUpdate (Animator animator, AnimatorStateInfo stateInfo, int layerIndex)

{

animator.transform.position = Vector2.MoveTowards (animator.transform.position, patrolPoints[randomPoint].transform.position, speed * Time.deltaTime);

if (Vector2.Distance (animator.transform.position, patrolPoints[randomPoint].transform.position) < 0.1f)

{

randomPoint = Random.Range (0, patrolPoints.Length);

}

}

override public void OnStateExit (Animator animator, AnimatorStateInfo stateInfo, int layerIndex)

{

}

}

So, programmers will experience a null reference exception on a single code line from this example. Therefore, we suggest scanning the code to locate the error. Prompts to you if you have managed to do so, but do not feel disappointed if you have not because we provide the answer.

Namely, the system shows the error due to the following command line:

animator.transform.position = Vector2.MoveTowards (animator.transform.position, patrolPoints[randomPoint].transform.position, speed * Time.deltaTime);

Although we can include other examples, it is time to learn how to debug the script.

Unity Object Reference Mistake: Quickest Solutions

You can debug the unity object reference error by filling out the empty objects. Fortunately, the message pinpoints the location and helps developers and programmers enable the script. However, our experts recommend placing strategic breakpoints and inspecting the variables by hovering the mouse over their names.

For example, you can check if the reference is set or not by right-clicking the word and choosing to Find all References. Furthermore, we will divide the solutions to help developers use them accordingly. For instance, we will show you a generic solution that does not require many elements and changes.

Look at the following example to fix the script:

ref1.ref2.ref3.member

var r1 = ref1;

var r2 = r1.ref2;

var r3 = r2.ref3;

r3.member

This immediate solution fixes the variables by providing correct references. In addition, this code follows a basic principle you can recreate in your document. However, developers can have an indirect approach to the matter.

This is how you can debug the script indirectly:

public class Person

{

public int Age { get; set; }

}

public class Book

{

public Person Author { get; set; }

}

public class Example

{

public void Foo()

{

Book b1 = new Book();

int authorAge = b1.Author.Age; // You never initialized the Author property.

// there is no Person to get an Age from.

}

}

This is everything you need to fix the mistake using a direct and indirect approach. However, this article offers two alternative solutions.

– Writing Nested Collection Initializers

Our team suggest writing nested collection initializers to remove the unity object reference mistake without affecting other functions. However, the syntax requires a few commands that create public classes with correct values.Unity Object Reference Not Set to an Instance of an Object Fixes

This example introduces the public classes:

public class Person

{

public ICollection<Book> Books { get; set; }

}

public class Book

{

public string Title { get; set; }

}

As you can tell, we kept the syntax short. However, this is only the first part because the developers must create initializers that react the same, as shown here:

Person p1 = new Person

{

Books = {

new Book { Title = “Title 1” },

new Book { Title = “Title 2” },

}

};

Consequently, the system renders the functions, and the code translates to the following syntax:

Person p1 = new Person();

p1.Books.Add (new Book { Title = “Title1” });

p1.Books.Add (new Book { Title = “Title2” });

The new value creates an instance for the old element, but the collection is still null. Nevertheless, the program will not launch the error because the initializer does not create a new collection for the component. Instead, it only translates the statements.

– Correct Life Cycles and Empty View Models

In this final section, we teach developers and programmers how to correct the life cycles and empty the view models to remove the mistake. We will show you examples that provide the solution, although developers might need to change the values and tags to fit their documents. In addition, both scripts have a few commands, so it would be easy for beginners to recreate them.

Our experts recommend correcting the life cycle, as shown here:

public partial class Issues_Edit : System.Web.UI.Page

{

protected TestIssue myIssue;

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

// Only called on first load, not when button clicked

myIssue = new TestIssue();

}

}

protected void SaveButton_Click(object sender, EventArgs e)

{

myIssue.Entry = “NullReferenceException here!”;

}

}

This code wraps up our expanded guide on debugging your script’s unity object reference error. Developers can learn more about the syntax in the following example:

// Controller

public class Restaurant:Controller

{

public ActionResult Search()

{

return View(); // Forgot the provide a Model here.

}

}

// Razor view

@foreach (var restaurantSearch in Model.RestaurantSearch) // Throws.

{

}

<p>@Model.somePropertyName</p> <!– Also throws –>

This code wraps up our expanded guide on debugging your script’s unity object reference error. Now, let us summarize the most important details.

Conclusion

The system does not set the unity object reference to an instance of an object when developers and programmers access an empty object in the script. This guide intends to help beginners and seasoned developers by explaining the following vital details:

  • The null reference confuses the system because it does not have anything to hold on to or reach inside the script
  • Game developers sometimes experience the same error with several commands in C#
  • This profound guide offers three standard solutions with examples that are easy to follow and repeat in your file
  • The total error message may have other elements, but the unity object reference bug remains unchanged

In addition, you can copy and paste the solutions, although changing several values might differ. Our team would be thrilled if this article helped you remove the annoying error script without much effort.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Добавить комментарий