ARGameLogic: Tutorial script issues - Others have same problem with this tutorial

Tutorial script produces error’s and wont function Others have same problem.

  • Problem category : tutorial script
  • Device type and OS version :windows 10
  • ARDK version :2.0.0
  • Unity version : 2020.3.30f1

Description of the issue:
Followed lesson, but script won’t run. I know others have had the same issue.

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

using Niantic.ARDK.AR;
using Niantic.ARDK.AR.Configuration;
using Niantic.ARDK.AR.ARSessionEventArgs;
using Niantic.ARDK.Extensions;
using System;

//using Niantic.ARDK.Configuration;
using Niantic.ARDK.Utilities.Input.Legacy;
using Niantic.ARDK.AR.HitTest;
using Niantic.ARDK.AR.WayspotAnchors;
using Niantic.ARDK.LocationService;
using System.Linq;


/// Creating and managing AR Anchors
public class ARGameLogic : MonoBehaviour
{
    private IARSession session;
    public Camera arCam;
    public GameObject objectPrefab;

    private WayspotAnchorService wayspotAnchorService;
    private bool InitalLocalisationFired = false;
    private readonly Dictionary<System.Guid, GameObject> anchors = new Dictionary<System.Guid, GameObject>();

    //store data to serialised key (mystoranchorsdata)
    private string localSaveKey = "my_wayspots";


    // Start is called before the first frame update
    void Start()
    {
        //create AR session
        session = ARSessionFactory.Create();
        ARSessionFactory.SessionInitialized += OnSessionInitialised;

        if (arCam == null)
        {
            Debug.Log("Camera not attached to script");
        }

    }

    private void OnSessionInitialised(AnyARSessionInitializedArgs args)
    {
        var configuration = ARWorldTrackingConfigurationFactory.Create();

        configuration.WorldAlignment = WorldAlignment.Gravity; //fixes drift issues whhile using tracking
        configuration.PlaneDetection = PlaneDetection.Horizontal; //must match

        configuration.IsLightEstimationEnabled = false;
        configuration.IsAutoFocusEnabled = false;
        configuration.IsDepthEnabled = false;
        configuration.IsSharedExperienceEnabled = false;


        // location service and wayspot anchor service initialization.
        session.Ran += OnSessionRan;
        session.Run(configuration);

        //9:10

    }

    void OnSessionStarted(ARSessionRanArgs args)
    {
        var wayspotAnchorsConfiguration = WayspotAnchorsConfigurationFactory.Create();

        var locationService = LocationServiceFactory.Create(session.RuntimeEnvironment);

        locationService.Start();

        wayspotAnchorService = new WayspotAnchorService(session, locationService, wayspotAnchorsConfiguration);
        ///15:53
    }

    private void OnSessionRan(ARSessionRanArgs args)
    {
        // throw new NotImplementedException();
    }

    //// Update is called once per frame
    void Update()
   {
        //    //skip any interaction while wayspot hasnt been localised
        if (wayspotAnchorService == null || wayspotAnchorService.LocalizationState != LocalizationState.Localized)
        {
            return;
        }

        //if service has been localise trigger a function
        if (wayspotAnchorService.LocalizationState == LocalizationState.Localized && !InitalLocalisationFired)
        {
            LoadLocalReference(); //ensure is only added once
            InitalLocalisationFired = true;
            //localisesation event fired once
            //TODO: EACH LOCALISATION STATE initialising , localising and localsing failed go here
            // each anchour point saved to playerprefs only if bool true

        }

        if (PlatformAgnosticInput.touchCount <= 0) return;
        var touch = PlatformAgnosticInput.GetTouch(0);

        if (touch.phase == TouchPhase.Began) 
        { 
            OnTapScreen(touch); 
        }

        //31:33
    }


    //// Sending the position to the Wayspot Service
    private void OnTapScreen(Touch touch)
    {
        var currentFrame = session.CurrentFrame;

        if (currentFrame == null) return;

    //    Debug.Log("OnTapScreen");

        var hitTestResults = currentFrame.HitTest(
            arCam.pixelWidth, 
            arCam.pixelHeight, 
            touch.position, 
            ARHitTestResultType.EstimatedHorizontalPlane
            );

        if (hitTestResults.Count <= 0) return;

        Matrix4x4 poseMatrix = hitTestResults[0].WorldTransform;

      //user taps screen to add an anchor and sends to wayspot service!

       AddAnchor(poseMatrix);


      ///12:45

    }

    private void AddAnchor(Matrix4x4 poseData)
    {
        Debug.Log("AddAnchor");
        wayspotAnchorService.CreateWayspotAnchors(OnWayspotAnchorsAdded, poseData);
    }


    //create gameobject and postions it at anchor
    //each anchor has an id
    private void OnWayspotAnchorsAdded(IWayspotAnchor[] wayspotAnchors)
    {
        foreach (var wayspotAnchor in wayspotAnchors)
        {
            if (anchors.ContainsKey(wayspotAnchor.ID)) continue;
            var id = wayspotAnchor.ID;
            var anchor = Instantiate(objectPrefab);
            anchor.SetActive(false);
            anchor.name = $"Anchor{id}";
            anchors.Add(id, anchor);

            wayspotAnchor.TrackingStateUpdated += OnUpdateAnchorPose;

            Debug.Log("OnWayspotAnchorsAdded + anchor.name" + anchor.name);
        }

     
      if (InitalLocalisationFired) SaveLocalReference();

        //31:50 
    }

    private void OnUpdateAnchorPose(WayspotAnchorResolvedArgs wayspotAnchorResolvedArgs)
    {
        Debug.Log("OnUpdateAnchorPose");
        //position anchor event
        var anchor = anchors[wayspotAnchorResolvedArgs.ID].transform;
        anchor.rotation = wayspotAnchorResolvedArgs.Rotation;
        anchor.position = wayspotAnchorResolvedArgs.Position;
        anchor.gameObject.SetActive(true);
        ///24:16
    }

    private void SaveLocalReference()
    {
        Debug.Log("SaveLocalReference");
        /* gets all anchours in the current session
         * stored as a payload onto myStoredAnchors
         * saves as serialsed content into player prefs so can be reloaded
         //this could also save the model, text, sound ID etc
         */

        IWayspotAnchor[] wayspotAnchors = wayspotAnchorService.GetAllWayspotAnchors();

        MyStoredAnchorsData storedAnchorsData = new MyStoredAnchorsData();

        storedAnchorsData.Payloads = wayspotAnchors.Select(a => a.Payload.Serialize()).ToArray();

        string jsonData = JsonUtility.ToJson(storedAnchorsData);
        PlayerPrefs.SetString(localSaveKey, jsonData);
        ///27:09
    }

    private void LoadLocalReference()
    {

        //Step 8: Loading locally stored data
        Debug.Log("LoadLocalReference");
        if (PlayerPrefs.HasKey(localSaveKey))
        {
            //update tracking and alignment
            //only works with localised state
            List<WayspotAnchorPayload> payloads = new List<WayspotAnchorPayload>();

            string json = PlayerPrefs.GetString(localSaveKey);
            MyStoredAnchorsData storedData = JsonUtility.FromJson<MyStoredAnchorsData>(json);

            foreach (var wayspotAnchorInPayload in storedData.Payloads)
            {
                var payload = WayspotAnchorPayload.Deserialize(wayspotAnchorInPayload);
                payloads.Add(payload);

            }


            if (payloads.Count > 0)
            {
                var waySpotAnchors = wayspotAnchorService.RestoreWayspotAnchors(payloads.ToArray());

                //creat the gameObjects
                OnWayspotAnchorsAdded(waySpotAnchors);
            }

            ///30:56 
        }
    }

    [Serializable]
    private class MyStoredAnchorsData
    {
        public string[] Payloads = Array.Empty<string>();
        //25:18
    }
}

Hi Natalie,
could you describe the problem a bit more in detail? Is it not compiling or has it problems on runtime? And where exactly?

Hello Natalie,

As @BBIT-Solutions requested, could you please give some more details in regards to how the script isn’t working and when you see the errors? If you could please provide a screenshot of your Console window in Unity to show the errors you’re seeing, it would greatly help us troubleshoot the issue.

If you’re having trouble instantiating your prefab, you can resolve that issue by going to your OnSessionInitialized() method and replacing the

session.Ran += OnSessionRan; with
session.Ran += OnSessionStarted;

And please be sure to review the other community members’ posts on this issue, such as this ARGameLogic.cs script error post. It outlines some issues that occurred while following this tutorial and how to solve them. Thank you!

1 Like

Thanks a lot that fixed it <3

OnSessionInitialized() method and replacing the

session.Ran += OnSessionRan; with
session.Ran += OnSessionStarted;