ARfoundation - Only want to spawn object once.

I’d like my object to only spawn once on the first tap of the screen. I’m creating a kids game and they tend to tap on the screen accidentally and as they look around but then they spawn the object again and its over the first one. Furthermore I have a placement indicator that needs to disappear as well after the first spawn of my object.

I’ve attached my code.

5028578–492800–My AR app Code.txt (2.13 KB)

private GameObject spawnedObject;

private void PlaceObject()
{
spawnedObject = Instantiate(objectToPlace, placementPose.position, placementPose.rotation);
}

void Update()
{

if (spawnedObject==null && placementPoseIsValid && Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
PlaceObject();
}
}

Hi linojon, Thanks for the reply. I’m pretty new to coding and I’m not sure if I should add the code or to replace it with what I had. I tried adding it but it doesn’t seem to work. Could you perhaps clarify this for me?

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

public class ARTapToPlaceObject : MonoBehaviour
{
public GameObject objectToPlace;
public GameObject IndicatorHolder;

private ARRaycastManager arOrigin;
private Pose placementPose;
private ARPlaneManager planeManager;

private bool placementPoseIsValid = false;
private GameObject spawnedObject;

void Start()
{

IndicatorHolder = GameObject.Find(“IndicatorHolder”);
arOrigin = FindObjectOfType();

}

// Update is called once per frame
void Update()
{
if (spawnedObject == null && placementPoseIsValid && Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
PlaceObject();
}

if (placementPoseIsValid && Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
PlaceObject();
}

UpdateIndicatorHolder();
UpdatePlacementPose();

}

private void PlaceObject()
{
spawnedObject = Instantiate(objectToPlace, placementPose.position, placementPose.rotation);
}

private void UpdateIndicatorHolder()
{
if (placementPoseIsValid)
{
IndicatorHolder.SetActive(true);
IndicatorHolder.transform.SetPositionAndRotation(placementPose.position, placementPose.rotation);
}
else
{
IndicatorHolder.SetActive(false);
}
}

private void UpdatePlacementPose()
{
var screenCenter = Camera.current.ViewportToScreenPoint(new Vector3(0.5f, 0.5f));
var hits = new List();
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);
}

}
}

Hi LinoJon, Thanks so much I got it working.

Thanks Lino for this