Y
Y
Yura Mailler2020-07-23 11:36:05
C++ / C#
Yura Mailler, 2020-07-23 11:36:05

I make an endless road but an error occurs: MissingReferenceException?

Hello everyone, I'm making a game (Runner) and I want to have an endless road and that if the character goes far, the road behind him will be destroyed. I already have the script, but when I start (Test) the game, I get the error MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object. (This is my first game so don't judge too harshly if it's very easy to solve :) )
codes :
first

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

public class Road : MonoBehaviour
{
    public List<GameObject> blocks; //Коллекция всех дорожных блоков
    public GameObject player; //Игрок
    public GameObject roadPrefab; //Префаб дорожного блока
    public GameObject carPrefab; //Префаб машины NPC
    public GameObject coinPrefab; //Префаб монеты

    private System.Random rand = new System.Random(); //Генератор случайных чисел

    void Update()
    {
        float x = player.GetComponent<Move>().rb.position.x; //Получение положения игрока

        var last = blocks[blocks.Count - 1]; //Номер дорожного блока, который дальше всех от игрока

        if (x > last.transform.position.x - 24.69f * 10f) //Если игрок подъехал к последнему блоку ближе, чем на 10 блоков
        {
            //Инстанцирование нового блока
            var block = Instantiate(roadPrefab, new Vector3(last.transform.position.x + 24.69f, last.transform.position.y, last.transform.position.z), Quaternion.identity);
            block.transform.SetParent(gameObject.transform); //Перемещение блока в объект Road
            blocks.Add(block); //Добавление блока в коллекцию

        }

        foreach (GameObject block in blocks)
        {
            bool fetched = block.GetComponent<RoadBlock>().Fetch(x); //Проверка, проехал ли игрок этот блок

            if (fetched) //Если проехал
            {
                blocks.Remove(block); //Удаление блока из коллекции
                block.GetComponent<RoadBlock>().Delete(); //Удаление блока со сцены
            }
        }
    }

}


second

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

public class RoadBlock : MonoBehaviour
{
    public bool Fetch(float x) //Проверка, проехала ли машина игрока этот блок на достаточное расстояние
    {
        bool result = false;

        if (x > transform.position.x + 10f)
        {
            result = true; //Если машина проехала на 10f от блока, то возвращается true
        }

        return result;
    }

    public void Delete()
    {
        Destroy(gameObject); //Удаление блока
    }  

}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
CHIDWI, 2020-07-23
@CHIDWI

Let each block decide for itself whether to delete it or not, and delete itself. Before deleting let him delete himself from the collection. This is advice if you do not understand the code.
It's just that somewhere in your code it tries to get an element that has already been removed and gives you an error. Check at what specific moment the error appears as an option.

A
Alexey, 2020-08-06
@aDOPPIO

You need to delete blocks from lists (sheets, arrays, etc.), it's just that you most likely fetch passes through the remote block.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question