Got a code from below, and exactly followed a youtube video. However, I wanted to test the code through the laptop cam. When I ran it, it displayed the following error:
NullReferenceException: Object reference not set to an instance of an object
ARPlacement.UpdatePlacementPose () (at Assets/Script/ARPlacement.cs:50)
ARPlacement.Update () (at Assets/Script/ARPlacement.cs:30)
Code is below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
public class ARPlacement : MonoBehaviour
{
public GameObject arObjectToSpawn;
public GameObject placementIndicator;
private GameObject spawnedObject;
private Pose PlacementPose;
private ARRaycastManager aRRaycastManager;
private bool placementPoseIsValid = false;
void Start()
{
aRRaycastManager = FindObjectOfType();
}
void Update()
{
if (spawnedObject == null && placementPoseIsValid && Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
ARPlaceObject();
}
UpdatePlacementPose();
UpdatePlacementIndicator();
}
void UpdatePlacementIndicator()
{
if (spawnedObject == null && placementPoseIsValid)
{
placementIndicator.SetActive(true);
placementIndicator.transform.SetPositionAndRotation(PlacementPose.position, PlacementPose.rotation);
}
else
{
placementIndicator.SetActive(false);
}
}
void UpdatePlacementPose()
{
var screenCenter = Camera.current.ViewportToScreenPoint(new Vector3(0.5f, 0.5f));
var hits = new List();
aRRaycastManager.Raycast(screenCenter, hits, TrackableType.Planes);
placementPoseIsValid = hits.Count > 0;
if (placementPoseIsValid)
{
PlacementPose = hits[0].pose;
}
}
void ARPlaceObject()
{
spawnedObject = Instantiate(arObjectToSpawn, PlacementPose.position, PlacementPose.rotation);
}
}