Я запускаю этот C# скрипт в Unity 3D для iOS приложения ARkit. Когда вызывается Update()
, он выполняет функцию UpdatePlacementPose()
. Я немедленно получаю журналы ошибок, в которых говорится:
update 2
UnityEngine.DebugLogHandler:Internal_Log(LogType, LogOption, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
ARTapToPlaceObject:Update()
(Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)
NullReferenceException: Object reference not set to an instance of an object.
at ARTapToPlaceObject.UpdatePlacementPose () [0x00000] in <00000000000000000000000000000000>:0
at ARTapToPlaceObject.Update () [0x00000] in <00000000000000000000000000000000>:0
(Filename: currently not available on il2cpp Line: -1)
Я запутался, потому что вызываемая функция не нуждается в экземпляре объекта, который должен быть вызван. Вот сценарий c#, который я написал:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR;
using UnityEngine.XR.ARSubsystems;
using System;
public class ARTapToPlaceObject : MonoBehaviour
{
public GameObject objectToPlace;
public GameObject placementIndicator;
private Camera myCamera;
private ARSessionOrigin arOrigin;
private ARRaycastManager raycastManager;
private Pose placementPose;
private bool placementPoseIsValid = false;
private void UpdatePlacementIndicator()
{
if (placementPoseIsValid)
{
placementIndicator.SetActive(true);
placementIndicator.transform.SetPositionAndRotation(placementPose.position, placementPose.rotation);
}
else
{
placementIndicator.SetActive(false);
}
}
private void UpdatePlacementPose()
{
var screenCenter = Camera.main.ViewportToScreenPoint(new Vector3(0.5f, 0.5f));
var hits = new List<ARRaycastHit>();
raycastManager.Raycast(screenCenter, hits, TrackableType.Planes);
Debug.Log("Screen: " + screenCenter);
Debug.Log("Hits: " + hits);
Debug.Log("Planes: " + TrackableType.Planes);
placementPoseIsValid = hits.Count > 0;
if (placementPoseIsValid)
{
placementPose = hits[0].pose;
Debug.Log("Hits Pose: " + hits[0].pose);
// var cameraForward = Camera.current.transform.forward;
// var cameraBearing = new Vector3(cameraForward.x, 0, cameraForward.z).normalized;
// placementPose.rotation = Quaternion.LookRotation(cameraBearing);
}
}
void Start()
{
arOrigin = FindObjectOfType<ARSessionOrigin>();
raycastManager = FindObjectOfType<ARRaycastManager>();
}
void Update()
{
Debug.Log("update 2");
UpdatePlacementPose();
Debug.Log("after updated placement pose");
UpdatePlacementIndicator();
if (placementPoseIsValid && Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
PlaceObject();
}
}
private void PlaceObject()
{
Instantiate(objectToPlace, placementPose.position, placementPose.rotation);
}
}
Любая помощь будет принята с благодарностью!