Nullreferenceexception object reference not set to an instance of an object unity как исправить

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.

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.

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.

[Решено]NullReferenceException: Object reference not set …

[Решено]NullReferenceException: Object reference not set …

Всем привет, При нажатие на кнопку открывается магазин и сразу же должны создаваться кнопки покупки или экипировки, все работало прекрасно, но в какойто момент перестало, вот ломаю голову что могло случиться, Помогите пожалуйста понять причину возникшей проблемы.

Вот ошибка. Выводит при срабатывание кейса shopbt
NullReferenceException: Object reference not set to an instance of an object
buttons.Active_but () (at Assets/Scripts/buttons.cs:98)

Вот скрипт buttons

Используется csharp

/// </summary>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class buttons : MonoBehaviour {

        public GameObject bg_shop; //переменная для изменения активности фона
        private GameObject main; // переменнная для изменения активности пиньяты
        public GameObject rp_act; //переменнная для изменения активности веревки
        private GameObject Bg_zk; //Закладки
        private Image im; //Для закладок
        private GameObject shop;
        public GameObject scroll, zakladka, knopka;

        public void Start(){
                main = GameObject.Find («Main Camera»);//Поиск объекта пиньяты в скрипте расположенном в Main Camera
                Bg_zk = GameObject.Find («Bg_Zakladka»);
                shop = GameObject.Find («shop»);
                im = Bg_zk.GetComponent<Image> ();
        }
        public void OnMouseUpAsButton(){ //Функция срабатывает когда убераешь палец имеено на объекте.
                switch (gameObject.name) { //Свитч для активации кнопки по имени
                case «shopbt»: //Активация магазина
                        bg_shop.SetActive (true);
                        //main.GetComponent<Vars> ().scroll [0].SetActive (true);
                        //main.GetComponent<Vars> ().zakladka [0].GetComponent<PolygonCollider2D> ().enabled = false;
                        scroll.SetActive (true);
                        zakladka.GetComponent<PolygonCollider2D> ().enabled = false;
                        main.GetComponent<CreatePinata> ().inst_pin.SetActive (false);
                        rp_act.SetActive (false);
                        //main.GetComponent<Vars> ().shopbut.SetActive (false);
                        knopka.SetActive(false);
                        main.GetComponent<CreatePinata> ().inst_stik.SetActive (false);
                        Invoke(«Active_but»,0.1f);
                        //shop.GetComponent<buttons_active_shop>().ActSt();
                        break;
        /*      case «shop_exit»:
                        shop.GetComponent<buttons_active_shop> ().Dest (0);
                        shop.GetComponent<buttons_active_shop> ().Dest (1);
                        main.GetComponent<Vars> ().scroll [0].SetActive (false);
                        main.GetComponent<Vars> ().scroll [1].SetActive (false);
                        main.GetComponent<Vars> ().scroll [2].SetActive (false);
                        main.GetComponent<Vars> ().zakladka [0].GetComponent<PolygonCollider2D> ().enabled = false;
                        main.GetComponent<Vars> ().zakladka [1].GetComponent<PolygonCollider2D> ().enabled = true;
                        main.GetComponent<Vars> ().zakladka [2].GetComponent<PolygonCollider2D> ().enabled = true;
                        im.sprite = main.GetComponent<Vars> ().pictZk [0];
                        bg_shop.gameObject.active = false;
                        main.GetComponent<CreatePinata> ().inst_pin.SetActive (true);
                        main.GetComponent<CreatePinata> ().inst_stik.SetActive (true);
                        rp_act.gameObject.active = true;
                        main.GetComponent<Vars> ().shopbut.SetActive (true);
                        main.GetComponent<CreatePinata> ().Save ();
                        break;
                case «St_col»:
                        shop.GetComponent<buttons_active_shop> ().Dest (1);
                        main.GetComponent<Vars>().scroll[0].SetActive(true);
                        main.GetComponent<Vars>().scroll[1].SetActive(false);
                        main.GetComponent<Vars>().scroll[2].SetActive(false);
                        main.GetComponent<Vars>().zakladka[0].GetComponent<PolygonCollider2D>().enabled = false;
                        main.GetComponent<Vars>().zakladka[1].GetComponent<PolygonCollider2D>().enabled = true;
                        main.GetComponent<Vars>().zakladka[2].GetComponent<PolygonCollider2D>().enabled = true;
                        im.sprite = main.GetComponent<Vars> ().pictZk [0];
                        shop.GetComponent<buttons_active_shop>().ActSt();
                        break;
                case «Pin_col»:
                        shop.GetComponent<buttons_active_shop>().Dest(0);
                        main.GetComponent<Vars>().scroll[0].SetActive(false);
                        main.GetComponent<Vars>().scroll[1].SetActive(true);
                        main.GetComponent<Vars>().scroll[2].SetActive(false);
                        main.GetComponent<Vars>().zakladka[0].GetComponent<PolygonCollider2D>().enabled = true;
                        main.GetComponent<Vars>().zakladka[1].GetComponent<PolygonCollider2D>().enabled = false;
                        main.GetComponent<Vars>().zakladka[2].GetComponent<PolygonCollider2D>().enabled = true;
                        im.sprite = main.GetComponent<Vars> ().pictZk [1];
                        shop.GetComponent<buttons_active_shop>().ActPn();
                break;
                case «Bg_col»:
                        shop.GetComponent<buttons_active_shop>().Dest(1);
                        shop.GetComponent<buttons_active_shop>().Dest(0);
                        main.GetComponent<Vars>().zakladka[0].GetComponent<PolygonCollider2D>().enabled = true;
                        main.GetComponent<Vars>().zakladka[1].GetComponent<PolygonCollider2D>().enabled = true;
                        main.GetComponent<Vars>().zakladka[2].GetComponent<PolygonCollider2D>().enabled = false;
                        main.GetComponent<Vars>().scroll[0].SetActive(false);
                        main.GetComponent<Vars>().scroll[1].SetActive(false);
                        main.GetComponent<Vars>().scroll[2].SetActive(true);
                        im.sprite = main.GetComponent<Vars> ().pictZk [2];
                        break;*/

                }
        }
        void Active_but () {
                shop.GetComponent<buttons_active_shop>().ActSt();
        }
}

Последний раз редактировалось Olmer 10 янв 2018, 23:03, всего редактировалось 1 раз.

Аватара пользователя
Olmer
UNец
 
Сообщения: 46
Зарегистрирован: 25 окт 2017, 21:54

Re: NullReferenceException: Object reference not set to an insta

Сообщение samana 10 янв 2018, 22:33

Что-то, где-то не назначено, либо потеряло ссылку.
Ошибка указывает на 98 строку, смотрите там. Можете кликнуть на ошибку в консоли и во второй, нижней половине этого же окна (консоли), будет более полное описание ошибки, в виде цепочки.

Аватара пользователя
samana
Адепт
 
Сообщения: 4733
Зарегистрирован: 21 фев 2015, 13:00
Откуда: Днепропетровск

Re: NullReferenceException: Object reference not set to an insta

Сообщение Olmer 10 янв 2018, 22:49

Вроде бы все на месте, 93 это вызов функции shop.GetComponent<buttons_active_shop>().ActSt();
В этом же скрипте этот вызов функции срабатывает при условии кейса case «St_col»: (переход по вкладкам), и тут все работает нормально и все кнопки он создает без проблем. Ссылки все на месте.

Аватара пользователя
Olmer
UNец
 
Сообщения: 46
Зарегистрирован: 25 окт 2017, 21:54

Re: NullReferenceException: Object reference not set to an insta

Сообщение Olmer 10 янв 2018, 23:02

Решил проблему, кинул ссылку переменной shop через инспектор,а не поиском (shop = GameObject.Find («shop»);) и заработало, но раньше и так работало.

Аватара пользователя
Olmer
UNец
 
Сообщения: 46
Зарегистрирован: 25 окт 2017, 21:54

Re: [Решено]NullReferenceException: Object reference not set …

Сообщение samana 10 янв 2018, 23:04

Может изменили имя с shop на Shop и забыли исправить имя в скрипте?

Аватара пользователя
samana
Адепт
 
Сообщения: 4733
Зарегистрирован: 21 фев 2015, 13:00
Откуда: Днепропетровск

Re: [Решено]NullReferenceException: Object reference not set …

Сообщение Olmer 10 янв 2018, 23:36

samana писал(а):Может изменили имя с shop на Shop и забыли исправить имя в скрипте?

Не менял, все также, ну явно я где-то что-то намутил и не заметил вовремя.

Аватара пользователя
Olmer
UNец
 
Сообщения: 46
Зарегистрирован: 25 окт 2017, 21:54


Вернуться в Почемучка

Кто сейчас на конференции

Сейчас этот форум просматривают: Google [Bot], Zimaell и гости: 19



Null Reference Exceptions

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:

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:

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:

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 Inspector A 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:

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.

NullReferenceException в Unity

Поскольку многие пользователи сталкиваются с NullReferenceException: Object reference not set to an instance of an object ошибкой в ​​Unity, я подумал, что было бы неплохо собрать из нескольких источников некоторые объяснения и способы исправления этой ошибки.

симптомы

Я получаю сообщение об ошибке ниже, появляющееся в моей консоли, что это значит и как я могу это исправить?

NullReferenceException: ссылка на объект не установлена ​​на экземпляр объекта

Тип значения против Тип ссылки

Во многих языках программирования переменные имеют так называемый «тип данных». Двумя основными типами данных являются типы значений (int, float, bool, char, struct, . ) и ссылочный тип (экземпляр классов). В то время как типы значений содержат само значение , ссылки содержат адрес памяти, указывающий на часть памяти, выделенную для хранения набора значений (аналогично C / C ++).

Например, Vector3 это тип значения (структура, содержащая координаты и некоторые функции), в то время как компоненты, прикрепленные к вашему GameObject (включая ваши собственные сценарии, наследуемые от MonoBehaviour ), являются ссылочным типом.

Когда я могу получить исключение NullReferenceException?

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

Некоторые общие места NullReferenceException будут подняты:

Управление GameObject / Component, который не был указан в инспекторе

Извлечение компонента, который не присоединен к GameObject, а затем попытка манипулировать им:

Доступ к GameObject, который не существует:

Примечание: Будьте осторожны, GameObject.Find , GameObject.FindWithTag , GameObject.FindObjectOfType возвращать только геймобжекты, которые включены в иерархии , когда функция вызывается.

Попытка использовать результат получателя, который возвращает null :

Доступ к элементу неинициализированного массива

Менее распространенный, но раздражающий, если вы не знаете об делегатах C #:

Как исправить ?

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

Проще сказать, чем сделать? Да, в самом деле. Вот несколько советов, чтобы избежать и определить проблему.

«Грязный» способ: метод try & catch:

«Чистый» способ (ИМХО): чек

Когда вы сталкиваетесь с ошибкой, которую вы не можете решить, всегда полезно найти причину проблемы. Если вы «ленивы» (или если проблему легко решить), используйте Debug.Log для отображения на консоли информацию, которая поможет вам определить причину проблемы. Более сложным способом является использование точек останова и отладчика вашей IDE.

Использование Debug.Log весьма полезно для определения, например, какая функция вызывается первой. Особенно, если у вас есть функция, отвечающая за инициализацию полей. Но не забудьте удалить их, Debug.Log чтобы не загромождать вашу консоль (и по соображениям производительности).

Еще один совет, не стесняйтесь «обрезать» свои вызовы функций и добавить, Debug.Log чтобы сделать некоторые проверки.

Сделайте это, чтобы проверить, установлены ли все ссылки:

Источники:

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

Например, это может быть ссылка на наш контроллер ввода. Здорово, что игра не вылетает из-за исключения с нулевой ссылкой, но нам нужно выяснить, почему нет контроллера ввода, и исправить эту проблему. Без этого у нас есть игра, которая может не рухнуть, но также не может принять ввод.

Ниже я перечислю возможные причины и решения, так как сталкиваюсь с ними в других вопросах.

Вы пытаетесь получить доступ к классу «менеджер»?

Если вы пытаетесь получить доступ к классу, который действует как «менеджер» (то есть, к классу, который должен иметь только один экземпляр за раз), вам лучше использовать подход Singleton . К классу Singleton в идеале можно обращаться откуда угодно, напрямую, сохраняя public static ссылку на себя. Таким образом, Singleton может содержать ссылку на активный экземпляр, который будет доступен без необходимости каждый раз устанавливать фактическую ссылку.

Вы ссылаетесь на экземпляр вашего объекта?

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

Вы инстанцируете свой экземпляр?

Если мы настраиваем наш объект в коде, важно убедиться, что мы создаем его экземпляр . Это может быть выполнено с использованием new ключевого слова и методов конструктора. Например, рассмотрим следующее:

Мы создали ссылку на a GameObject , но она ни на что не указывает. Доступ к этой ссылке как есть приведет к исключению пустой ссылки . Прежде чем ссылаться на наш GameObject экземпляр, мы можем вызвать метод конструктора по умолчанию следующим образом:

Учебник Unity по классам объясняет практику создания и использования конструкторов.

Используете ли вы GetComponent<t>() метод с предположением, что компонент существует?

Во-первых, убедитесь, что мы всегда вызываем GetComponent<t>() до вызова методов из экземпляра компонента.

По причинам, не заслуживающим внимания, мы можем предположить, что наш локальный игровой объект содержит определенный компонент, и попытаться получить к нему доступ GetComponent<t>() . Если локальный игровой объект не содержит этот конкретный компонент, мы вернем null значение.

Вы можете легко проверить, является ли возвращаемое значение null , до доступа к нему. Однако, если ваш игровой объект должен иметь обязательный компонент, может быть лучше убедиться, что он по крайней мере имеет версию этого компонента по умолчанию . Мы можем пометить MonoBehaviour как, [RequireComponent(typeof(t))] чтобы гарантировать, что у нас всегда есть этот тип компонента.

Вот пример MonoBehaviour для игрового объекта, который всегда должен содержать Rigidbody . Если сценарий добавляется к игровому объекту, который не содержит Rigidbody , создается значение по умолчанию Rigidbody .

Вы пытались пересобрать свой проект?

В некоторых случаях Unity может вызвать проблемы, пытаясь ссылаться на кэшированную версию игрового объекта. В соответствии со старым решением «выключите и снова включите», попробуйте удалить папку библиотеки и заново открыть Unity. Unity будет вынуждена пересобрать ваш проект. Это может решить некоторые очень специфические случаи этой проблемы и должно указывать на проблемы, которые не возникнут в окончательной сборке.

NullReferenceException: Object reference not set to an instance of an object #351

Right after installing the extenstion, and opening the Github Window the console is spammed with errors and the window is blank. The settings window works tho.

Steps to Reproduce

  1. [First Step]
    Install Github for Unity
  2. [Second Step]
    Open the Github Window
  3. [and so on. ]
    Look at console

Expected behavior: [What you expect to happen]
For the window to show up with no errors
Actual behavior: [What actually happens]
The window is blank and there are errors
Reproduces how often: [What percentage of the time does it reproduce?]
100% of the time

Сама ошибка вот такая:NullReferenceException: Object reference not set to an instance of an objectGameContoller.MoveLevelTop (Level level) (at Assets/Scripts/GameContoller.cs:107)Level.LateUpdate () (at Assets/Scripts/Level.cs:48)

107 строчка — level.Setup(new Vector3(0, lastLevel.AnchoredPosition.y + lastLevel.Size.y), colors[CurrentLevel % colors.Count], CurrentLevel);

48 строчка — OnFinishLevel?.Invoke(this);

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

public class Level : MonoBehaviour
{
public System.Action OnStartNewLevel;
public System.Action<Level> OnFinishLevel;

private RectTransform rect;
private Image image;
private bool newLevelFired;
[SerializeField] Text levelText;

public Vector3 AnchoredPosition { get { return rect.anchoredPosition3D; } set { rect.anchoredPosition3D = value;}}
public Vector2 Size { get { return rect.sizeDelta; } set { rect.sizeDelta = value; } }

public Color BackColor { get {return image.color; } set { image.color = value; } }

private void Awake() {
image = GetComponent<Image>();
rect = GetComponent<RectTransform>();
}
void Start()
{

}

// Update is called once per frame
void Update()
{
if (GameContoller.Instance.State == GameContoller.GameState.PLAY)
{
AnchoredPosition += Vector3.down * Time.deltaTime * 400;
}
}

private void LateUpdate() {
if (!newLevelFired && AnchoredPosition.y < 500)
{
OnStartNewLevel?.Invoke();
newLevelFired = true;
}
if (AnchoredPosition.y < -Size.y — 100)
{
OnFinishLevel?.Invoke(this);
}
}

public void Setup(Vector3 pos, Color color, int level)
{
newLevelFired = false;
AnchoredPosition = pos;
BackColor = color;
levelText.text = level.ToString();
}
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class GameContoller : MonoBehaviour
{
public enum GameState { START, PLAY, LOSE, GAME_OVER};
public event System.Action<GameState> OnStateChanged;
public event System.Action<int> OnCurrentLevelChanged;
public event System.Action<int> OnScoreChanged;
public System.Action<int> OnGameOver;
private GameState state;
private int currentLevel;
private int score;
[SerializeField] private Transform levelRegion = null;
[SerializeField] private Level LevelPrefab = null;
[SerializeField] private List<Color> colors = new List<Color>();
[SerializeField] private Player player;
private List<Level> levels = new List<Level>();
private List <GameObject> ObstaclePrefabs ;

public GameState State { get => state; set { state = value; OnStateChanged?.Invoke(state);} }

public int CurrentLevel { get => currentLevel; set { currentLevel = value; OnCurrentLevelChanged?.Invoke(value); } }

public int Score { get => score; set { score = value; OnScoreChanged?.Invoke(value); } }

public static GameContoller Instance;
[SerializeField] private Transform spawnRegion;
private Level lastLevel;

private void Awake()
{
Instance = this;
}

private void Start()
{
ObstaclePrefabs = Resources.LoadAll<GameObject>(«GroupObstacles»).ToList();

for (int i=0; i<2;i++)
{
levels.Add(SpawnNewLevel1());

}
ResetLevels();
player.OnGameOver += GameOver;
}

private void GameOver()
{
State = GameState.LOSE;
StartCoroutine(DelayAction(1.5f,()=> {
State = GameState.GAME_OVER;
ResetGame();
OnGameOver.Invoke(Score);

}));
}

public void ResetGame()
{
ClearObstacle();
ResetLevels();
player.Reset();
}

private void ClearObstacle()
{
foreach (Transform child in spawnRegion.transform)
{
Destroy(child.gameObject);
}
}

private IEnumerator DelayAction(float delay, System.Action action)
{
yield return new WaitForSeconds(delay);
action();
}

private void ResetLevels()
{
levels[0].AnchoredPosition = new Vector3(0, -levels[0].Size.y / 2);
for ( int i = 1; i < levels.Count; i ++)
{
levels[i].AnchoredPosition = new Vector3(0, levels[i — 1].AnchoredPosition.y + levels[ i- 1].Size.y);
}
}
private Level SpawnNewLevel1()
{
Level level = Instantiate(LevelPrefab, Vector3.zero, Quaternion.identity, levelRegion);
level.AnchoredPosition =Vector3.zero;
level.BackColor = colors[UnityEngine.Random.Range(0, colors.Count)];
level.Size = new Vector2 (levelRegion.parent.GetComponent<RectTransform>().sizeDelta.x, levelRegion.parent.GetComponent<RectTransform>().sizeDelta.y * 2 );
level.OnFinishLevel += MoveLevelTop;
level.OnStartNewLevel += () => { CurrentLevel++; };
return level;
}

private void MoveLevelTop (Level level)
{
level.Setup(new Vector3(0, lastLevel.AnchoredPosition.y + lastLevel.Size.y), colors[CurrentLevel % colors.Count], CurrentLevel);
lastLevel = level;
SpawnObstacle(ObstaclePrefabs[UnityEngine.Random.Range(0, ObstaclePrefabs.Count )], spawnRegion);
//level.AnchoredPosition = new Vector3(0, lastLevel.AnchoredPosition.y + lastLevel.Size.y);
}

public void StartGame()
{ CurrentLevel = 1;
Score = 0;
State = GameState.PLAY;
SpawnObstacle(ObstaclePrefabs[UnityEngine.Random.Range(0, ObstaclePrefabs.Count)], spawnRegion);
StartCoroutine(ScoreCoroutine());
}

private IEnumerator ScoreCoroutine()
{
while (State == GameState.PLAY)
{
Score++;
yield return new WaitForSeconds(0.2f);
}
}
private void SpawnObstacle(GameObject gameObject, Transform spawnRegion, bool isFirst= false)
{
Instantiate(gameObject, spawnRegion.transform.position * (isFirst ? 0.5f : 1), Quaternion.identity, spawnRegion);
}

}

Хочу чтобы префаб Level спавнился, когда проходим границы Level. Мы перемещаем новый уровень вверх, пересоздавая его. Но вот скрипт не работает , вылазит вот такая ошибка, когда прохожу границы Level

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Null is null not an object error
  • Nuke error writing frame to file
  • Not an srep compressed file как исправить
  • Not all control paths return a value как исправить
  • Not all arguments converted during string formatting питон ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии