SteamworksAchievements.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Sirenix.OdinInspector;
  5. using KairoEngine.Core;
  6. namespace KairoEngine.SteamIntegration
  7. {
  8. [System.Serializable]
  9. public class SteamworksAchievements
  10. {
  11. [Tooltip("Listen for internal game events for when an achievement is unlocked")]
  12. public bool listenForUnlockEvents = true;
  13. [ShowIf("@listenForUnlockEvents")] public string listenEventName = "AchievementUnlockedEvent";
  14. [Tooltip("Fire an event when an achievement is unlocked in the Steam backend")]
  15. public bool broadcastEventOnUnlock = true;
  16. [ShowIf("@broadcastEventOnUnlock")] public string broadcastEventName = "SteamAchievementUnlocked";
  17. public void Start()
  18. {
  19. if(listenForUnlockEvents) GenericEvents.StartListening(listenEventName, UnlockAchievement);
  20. if(broadcastEventOnUnlock) Steamworks.SteamUserStats.OnAchievementProgress += AchievementChanged;
  21. }
  22. public void Stop()
  23. {
  24. if(listenForUnlockEvents) GenericEvents.StopListening(listenEventName, UnlockAchievement);
  25. if(broadcastEventOnUnlock) Steamworks.SteamUserStats.OnAchievementProgress -= AchievementChanged;
  26. }
  27. private void AchievementChanged( Steamworks.Data.Achievement ach, int currentProgress, int progress )
  28. {
  29. if ( ach.State )
  30. {
  31. Debug.Log( $"{ach.Name} WAS UNLOCKED!" );
  32. GenericEvents.Trigger(broadcastEventName, ach.Identifier);
  33. }
  34. }
  35. [Button("Unlock Achievement")]
  36. public void UnlockAchievement(string achievementId)
  37. {
  38. if(!SteamworksManager.HasInitialized()) return;
  39. var achievements = Steamworks.SteamUserStats.Achievements;
  40. foreach (var achievement in achievements)
  41. {
  42. if(achievement.Identifier == achievementId)
  43. {
  44. if(achievement.State == false)
  45. {
  46. achievement.Trigger();
  47. Steamworks.SteamUserStats.StoreStats();
  48. Debug.Log($"UNLOCKED achievement {achievementId} on Steam");
  49. }
  50. else Debug.Log($"Achievement {achievementId} already UNLOCKED on Steam");
  51. return;
  52. }
  53. }
  54. }
  55. [ButtonGroup("Buttons"),Button("Print Achievements")]
  56. public void PrintAchievementStatus()
  57. {
  58. if(!SteamworksManager.HasInitialized()) return;
  59. var achievements = Steamworks.SteamUserStats.Achievements;
  60. foreach (var achievement in achievements)
  61. {
  62. Debug.Log($"{achievement.Name} ({(achievement.State ? "UNLOCKED" : "LOCKED")} - {achievement.Identifier})");
  63. }
  64. }
  65. }
  66. }