如何保存一个禁用的游戏对象?

huangapple go评论98阅读模式
英文:

How to save a disabled Game object?

问题

当我在游戏中点击按钮时,它会从脚本中禁用:

  1. MyGameobject.SetActive(false)

但问题是,当我重新启动游戏时,已禁用的游戏对象会再次启用。所以我的问题是,如何保存已禁用的游戏对象?

我尝试使用PlayerPrefs,但我意识到这没有意义。或者有吗?

英文:

So I have a button in my game and when I click it, it disables from script

  1. MyGameobject.SetActive(false)

But the problem is that when I restart the game the disabled gameobject is enabled again. So my question is how do I save the disabled gameobject ?

I tried using PlayerPrefs, but I realised that it makes no sense. Or does it?

答案1

得分: 1

使用 PlayerPrefs

  1. public GameObject MyGameObject;
  2. void Start()
  3. {
  4. // 检查启动时游戏对象应该是启用还是禁用的
  5. if (PlayerPrefs.GetInt("MyGoActiveState") == 0)
  6. {
  7. // 应该被禁用
  8. MyGameObject.SetActive(false);
  9. }
  10. else
  11. {
  12. // 应该被启用
  13. MyGameObject.SetActive(true);
  14. }
  15. }
  16. // 假设这是禁用对象的回调
  17. public void DisableGameObject()
  18. {
  19. // 禁用游戏对象
  20. MyGameObject.SetActive(false);
  21. // 在 PlayerPrefs 中存储游戏对象已被禁用
  22. PlayerPrefs.SetInt("MyGoActiveState", 0);
  23. }
  24. // 假设这是启用对象的回调
  25. public void EnableGameObject()
  26. {
  27. // 启用游戏对象
  28. MyGameObject.SetActive(true);
  29. // 在 PlayerPrefs 中存储游戏对象已被启用
  30. PlayerPrefs.SetInt("MyGoActiveState", 1);
  31. }
  32. 对于喜欢一行代码的人,也可以像这样设置活动状态,假设 0 用于指示禁用,而其他任何值都表示启用:
  33. ```csharp
  34. MyGameObject.SetActive(PlayerPrefs.GetInt("MyGoActiveState") == 0);
英文:

Using PlayerPrefs:

  1. public GameObject MyGameObject;
  2. void Start()
  3. {
  4. // Check on start if gameobject should be enabled or disabled
  5. if (PlayerPrefs.GetInt("MyGoActiveState") == 0)
  6. {
  7. // Should be disabled
  8. MyGameObject.SetActive(false);
  9. }
  10. else
  11. {
  12. // Should be enabled
  13. MyGameObject.SetActive(true);
  14. }
  15. }
  16. // Assuming this is your callback for disabling the object
  17. public void DisableGameObject()
  18. {
  19. // Disable gameobject
  20. MyGameObject.SetActive(false);
  21. // Store in PlayerPrefs that gameobject is disabled
  22. PlayerPrefs.SetInt("MyGoActiveState", 0);
  23. }
  24. // Assuming this is your callback for enabling the object
  25. public void EnableGameObject()
  26. {
  27. // Enable gameobject
  28. MyGameObject.SetActive(true);
  29. // Store in PlayerPrefs that gameobject is enabled
  30. PlayerPrefs.SetInt("MyGoActiveState", 1);
  31. }

For one-line fans one could also set the active state like this, assuming 0 is used to indicate disabled and anything else means enabled:

  1. MyGameObject.SetActive(PlayerPrefs.GetInt("MyGoActiveState") == 0);

huangapple
  • 本文由 发表于 2023年2月8日 16:45:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定