AR my objects disappear when I attach script to them. What am I missing?
Hi, everyone!
I'm new to Unity and I have a task of creating an object that appears upon tap. I'm working along this tutorial: https://youtu.be/Ml2UakwRxjk
The problem is that when I just place a cube, bulid&run, the cube appears floating, just like in the tutorial. Than I create a placement indicator and follow along the tutorial with code.
When I finish it, hit build&run, both placement indicator and the object disappear. They're visible before I attach the C# script. What am I missing? I re-wrote the code by hand to make sure everything is where is should be. Tried everything I could think of and still the same result - empty device viewport. Pls help.
The code is here:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.XR.ARFoundation; using UnityEngine.Experimental.XR; using System;
public class ARTapToPlaceObject : MonoBehaviour { public GameObject objectToPlace; public GameObject placementIndicator;
private ARSessionOrigin arOrigin;
private Pose placementPose;
private bool placementPoseIsValid = false;
void Start()
{
arOrigin = FindObjectOfType<ARSessionOrigin>();
}
void Update()
{
UpdatePlacementPose();
UpdatePlacementIndicator();
if (placementPoseIsValid && Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
PlaceObject();
}
}
private void PlaceObject()
{
Instantiate(objectToPlace, placementPose.position, placementPose.rotation);
}
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.current.ViewportToScreenPoint(new Vector3(0.5f, 0.5f));
var hits = new List<ARRaycastHit>();
arOrigin.Raycast(screenCenter, hits, TrackableType.Planes);
placementPoseIsValid = hits.Count > 0;
if (placementPoseIsValid)
{
placementPose = hits[0].pose;
var cameraForward = Camera.current.transform.forward;
var cameraBearing = new Vector3(cameraForward.x, 0, cameraForward.z).normalized;
placementPose.rotation = Quaternion.LookRotation(cameraBearing);
}
}
}