
Вопрос задан 04.06.2023 в 02:06.
Предмет Информатика.
Спрашивает Смирнов Евгений.
Только начинаю работать в Unity, помогите пожалуйста. Ошибка в Unity: "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. GameController.Update () (at Assets/Scripts/GameController.cs:49)" Вот код: using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class GameController : MonoBehaviour { private CubePos nowCube = new CubePos(0, 1, 0); public float cubeChangePlaceSpeed = 0.5f; public Transform cubeToPlace; public GameObject cubeToCreate, allCubes; private Rigidbody allCubesRb; private bool IsLose; private List allCubesPositions = new List { new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(1, 0, 1), new Vector3(-1, 0, -1), new Vector3(-1, 0, 1), new Vector3(1, 0, -1), }; private Coroutine showCubePlace; private void Start() { allCubesRb = allCubes.GetComponent(); showCubePlace = StartCoroutine(ShowCubePlace()); } private void Update() { if ((Input.GetMouseButtonDown(0) || Input.touchCount > 0) && cubeToPlace != null) { #if !UNITY_EDITOR if(Input.GetTouch(0).phase != TouchPhase.Began) return; #endif GameObject newCube = Instantiate(cubeToCreate, cubeToPlace.position, Quaternion.identity) as GameObject; newCube.transform.SetParent(allCubes.transform); nowCube.setVector(cubeToPlace.position); allCubesPositions.Add(nowCube.getVector()); allCubesRb.isKinematic = true; allCubesRb.isKinematic = false; SpawnPosition(); } if (IsLose && allCubesRb.velocity.magnitude > 0.1f) { Destroy(cubeToPlace.gameObject); IsLose = true; StopCoroutine(showCubePlace); } } IEnumerator ShowCubePlace() { while (true) { SpawnPosition(); yield return new WaitForSeconds(cubeChangePlaceSpeed); } } private void SpawnPosition() { List positions = new List(); if (IsPositionEmpty(new Vector3(nowCube.x + 1, nowCube.y, nowCube.z)) && nowCube.x + 1 != cubeToPlace.position.x) positions.Add(new Vector3(nowCube.x + 1, nowCube.y, nowCube.z)); if (IsPositionEmpty(new Vector3(nowCube.x - 1, nowCube.y, nowCube.z)) && nowCube.x - 1 != cubeToPlace.position.x) positions.Add(new Vector3(nowCube.x - 1, nowCube.y, nowCube.z)); if (IsPositionEmpty(new Vector3(nowCube.x, nowCube.y + 1, nowCube.z)) && nowCube.y + 1 != cubeToPlace.position.y) positions.Add(new Vector3(nowCube.x, nowCube.y + 1, nowCube.z)); if (IsPositionEmpty(new Vector3(nowCube.x, nowCube.y - 1, nowCube.z)) && nowCube.y - 1 != cubeToPlace.position.y) positions.Add(new Vector3(nowCube.x, nowCube.y - 1, nowCube.z)); if (IsPositionEmpty(new Vector3(nowCube.x, nowCube.y, nowCube.z + 1)) && nowCube.z + 1 != cubeToPlace.position.z) positions.Add(new Vector3(nowCube.x, nowCube.y, nowCube.z + 1)); if (IsPositionEmpty(new Vector3(nowCube.x, nowCube.y, nowCube.z - 1)) && nowCube.z - 1 != cubeToPlace.position.z) positions.Add(new Vector3(nowCube.x, nowCube.y, nowCube.z - 1)); cubeToPlace.position = positions[UnityEngine.Random.Range(0, positions.Count)]; } private bool IsPositionEmpty(Vector3 targetPos) { if (targetPos.y == 0) return false; foreach (Vector3 pos in allCubesPositions) if (pos.x == targetPos.x && pos.y == targetPos.y && pos.z == targetPos.z) return false; return true; } } struct CubePos { public int x, y, z; public CubePos(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public Vector3 getVector() { return new Vector3(x, y, z); } public void setVector(Vector3 pos) { x = Convert.ToInt32(pos.x); y = Convert.ToInt32(pos.y); z = Convert.ToInt32(pos.z); } }

Ответы на вопрос

Отвечает Костоусова Леся.
Объект типа "GameObject", уничтожен, но в коде ты к нему обращаешься. Если он не уничтожен, то присвой ему значение null в начале.



Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.
Проблема возникает из-за того, что вы пытаетесь обратиться к объекту cubeToPlace
, который был уничтожен, но не проверяете его наличие перед использованием. Вам необходимо добавить проверку на null
перед обращением к объекту cubeToPlace
.
Вот исправленный код с добавленной проверкой:
csharpusing UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class GameController : MonoBehaviour
{
private CubePos nowCube = new CubePos(0, 1, 0);
public float cubeChangePlaceSpeed = 0.5f;
public Transform cubeToPlace;
public GameObject cubeToCreate, allCubes;
private Rigidbody allCubesRb;
private bool IsLose;
private List<Vector3> allCubesPositions = new List<Vector3>
{
new Vector3(0, 0, 0),
new Vector3(1, 0, 0),
new Vector3(-1, 0, 0),
new Vector3(0, 1, 0),
new Vector3(0, 0, 1),
new Vector3(0, 0, -1),
new Vector3(1, 0, 1),
new Vector3(-1, 0, -1),
new Vector3(-1, 0, 1),
new Vector3(1, 0, -1)
};
private Coroutine showCubePlace;
private void Start()
{
allCubesRb = allCubes.GetComponent<Rigidbody>();
showCubePlace = StartCoroutine(ShowCubePlace());
}
private void Update()
{
if ((Input.GetMouseButtonDown(0) || Input.touchCount > 0) && cubeToPlace != null)
{
#if !UNITY_EDITOR
if (Input.GetTouch(0).phase != TouchPhase.Began)
return;
#endif
GameObject newCube = Instantiate(cubeToCreate, cubeToPlace.position, Quaternion.identity) as GameObject;
newCube.transform.SetParent(allCubes.transform);
nowCube.setVector(cubeToPlace.position);
allCubesPositions.Add(nowCube.getVector());
allCubesRb.isKinematic = true;
allCubesRb.isKinematic = false;
SpawnPosition();
}
if (IsLose && allCubesRb.velocity.magnitude > 0.1f)
{
if (cubeToPlace != null)
Destroy(cubeToPlace.gameObject);
IsLose = true;
StopCoroutine(showCubePlace);
}
}
IEnumerator ShowCubePlace()
{
while (true)
{
SpawnPosition();
yield return new WaitForSeconds(cubeChangePlaceSpeed);
}
}
private void SpawnPosition()
{
List<Vector3> positions = new List<Vector3>();
if (IsPositionEmpty(new Vector3(nowCube.x + 1, nowCube.y, nowCube.z)) && nowCube.x + 1 != cubeToPlace.position.x)
positions.Add(new Vector3(nowCube.x + 1, nowCube.y, nowCube.z));
if (IsPositionEmpty(new Vector3(nowCube.x - 1, nowCube.y, nowCube.z)) && nowCube.x - 1 != cubeToPlace.position.x)
positions.Add(new Vector3(nowCube.x - 1, nowCube.y, nowCube.z));
if (IsPositionEmpty(new Vector3(now


Топ вопросов за вчера в категории Информатика
Последние заданные вопросы в категории Информатика
Предметы
-
Математика
-
Литература
-
Алгебра
-
Русский язык
-
Геометрия
-
Английский язык
-
Химия
-
Физика
-
Биология
-
Другие предметы
-
История
-
Обществознание
-
Окружающий мир
-
География
-
Українська мова
-
Информатика
-
Українська література
-
Қазақ тiлi
-
Экономика
-
Музыка
-
Право
-
Беларуская мова
-
Французский язык
-
Немецкий язык
-
МХК
-
ОБЖ
-
Психология
-
Физкультура и спорт
-
Астрономия
-
Кыргыз тили
-
Оʻzbek tili