using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.XR.ARFoundation; using UnityEngine.XR.ARSubsystems; namespace AR { public class TrackedImageChanged : MonoBehaviour { [SerializeField] ARTrackedImageManager m_TrackedImageManager; [SerializeField] private List _arTrackedImagePrefabs = new (); private List _spawned = new (); #if UNITY_EDITOR [Header("Debug")] [SerializeField] private InputAction m_DebugListImages; #endif void OnEnable() { m_TrackedImageManager.trackedImagesChanged += OnChange; #if UNITY_EDITOR m_DebugListImages.Enable(); m_DebugListImages.performed += Debug_ListImages; #endif } void OnDisable() { m_TrackedImageManager.trackedImagesChanged -= OnChange; #if UNITY_EDITOR m_DebugListImages.performed -= Debug_ListImages; m_DebugListImages.Disable(); #endif } private void OnChange(ARTrackedImagesChangedEventArgs eventArgs) { foreach (var newImage in eventArgs.added) { // Handle added event Debug.Log($"Added image: {newImage.referenceImage.name}"); foreach (var prefab in _arTrackedImagePrefabs) { if (prefab.referenceImage.name.Equals(newImage.referenceImage.name)) { if (_spawned == null) { _spawned = new List(); } // Spawn new object Debug.Log("Spawning object..."); _spawned.Add(Instantiate(prefab, newImage.transform)); } } } foreach (var updatedImage in eventArgs.updated) { // Handle updated event Debug.Log($"Updated image: {updatedImage.trackableId} - {updatedImage.trackingState}"); foreach (var spawnedObject in _spawned) { if (spawnedObject.trackableId == updatedImage.trackableId) { // Update position Debug.Log("Updating position..."); spawnedObject.transform.position = updatedImage.transform.position; } } } foreach (var removedImage in eventArgs.removed) { // Handle removed event Debug.Log($"Removed image: {removedImage.referenceImage.name}"); for (int i = _spawned.Count - 1; i >= 0; i--) { var spawnedObject = _spawned[i]; if (spawnedObject.trackableId == removedImage.trackableId) { // Handle object removal Debug.Log("Removing object..."); if (_spawned.Remove(spawnedObject)) { // Destroy object Debug.Log("Destroying object..."); Destroy(spawnedObject.gameObject); } } } } } private void ListAllImages() { Debug.Log( $"There are {m_TrackedImageManager.trackables.count} images being tracked."); foreach (var trackedImage in m_TrackedImageManager.trackables) { Debug.Log($"Image: {trackedImage.referenceImage.name} is at " + $"{trackedImage.transform.position}"); } } private ARTrackedImage GetImageAt(TrackableId trackableId) { return m_TrackedImageManager.trackables[trackableId]; } private void Debug_ListImages(InputAction.CallbackContext _) => ListAllImages(); } }