1

Пытаюсь сделать основу vr игры по туториалу, но тут всплыла проблема NullReferenceException: Object reference not set to an instance of an object HandPresence.Update () (at Assets/HandPresence.cs:56) и из-за этой проблемы у меня на контроллерах отображается и контроллеры и "руки". Пытался убирать некоторые части кода и после того как убрать код в update ничего не меняется. введите сюда описание изображения

вот сам код (пометил 56 строку) и вот ссылка на видео человека с таймкодом https://youtu.be/VdT0zMcggTQ?t=912

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

public class HandPresence : MonoBehaviour { public bool showController = false; public InputDeviceCharacteristics controllerCharacteristics; public List<GameObject> controllerPrefabs; public GameObject handModelPrefab;

private InputDevice targetDevice;
private GameObject spawnedController;
private GameObject spawnedHandModel;

// Start is called before the first frame update
void Start()
{
    List&lt;InputDevice&gt; devices = new List&lt;InputDevice&gt;();
    // InputDeviceCharacteristics rightControllerCharacteristics = InputDeviceCharacteristics.Right | InputDeviceCharacteristics.Controller;
    InputDevices.GetDevicesWithCharacteristics(controllerCharacteristics, devices);

    foreach (var item in devices)
    {
        Debug.Log(item.name + item.characteristics);
    }
    if (devices.Count &gt; 0) 
    {
        targetDevice = devices[0];
        GameObject prefab = controllerPrefabs.Find(controller =&gt; controller.name == targetDevice.name);
        if (prefab)
        {
            Instantiate(prefab, transform);
        }
        else
        {
            Debug.LogError(&quot;Did not find corresponding controller model&quot;);
            spawnedController = Instantiate(controllerPrefabs[0], transform);
        }

        spawnedHandModel = Instantiate(handModelPrefab, transform);
    }
}

// Update is called once per frame
void Update()
{
    if(showController)
    {
        spawnedHandModel.SetActive(false);
        spawnedController.SetActive(true);
    }
    else
    {
        spawnedController.SetActive(false); // 56 строка
        spawnedHandModel.SetActive(true);
    }
}

}

1 Answers1

2

Полагаю, что надо так:

    if (prefab)
    {
        spawnedController = Instantiate(prefab, transform); # исправил эту строку
    }
    else
    {
        Debug.LogError("Did not find corresponding controller model");
        spawnedController = Instantiate(controllerPrefabs[0], transform);
    }

Иначе при выполнении условия if (prefab) у вас spawnedController остаётся не инициализированным и потом вылазит ошибка как-раз про это. Я так то Unity 3D уже не помню, хотя и изучал, но по логике выходит как-то так.

CrazyElf
  • 71,194
  • О боже спасибо. Всем дискордом пытались найти ошибку и не получалось. А вы так быстро посмотрели и исправили. Благодарю всем сердцем. – Easyman121 Jun 30 '20 at 20:34
  • Без вас бы голову ломал неделю так точно – Easyman121 Jun 30 '20 at 20:35