英文:
How to save a disabled Game object?
问题
当我在游戏中点击按钮时,它会从脚本中禁用:
MyGameobject.SetActive(false)
但问题是,当我重新启动游戏时,已禁用的游戏对象会再次启用。所以我的问题是,如何保存已禁用的游戏对象?
我尝试使用PlayerPrefs,但我意识到这没有意义。或者有吗?
英文:
So I have a button in my game and when I click it, it disables from script
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
:
public GameObject MyGameObject;
void Start()
{
// 检查启动时游戏对象应该是启用还是禁用的
if (PlayerPrefs.GetInt("MyGoActiveState") == 0)
{
// 应该被禁用
MyGameObject.SetActive(false);
}
else
{
// 应该被启用
MyGameObject.SetActive(true);
}
}
// 假设这是禁用对象的回调
public void DisableGameObject()
{
// 禁用游戏对象
MyGameObject.SetActive(false);
// 在 PlayerPrefs 中存储游戏对象已被禁用
PlayerPrefs.SetInt("MyGoActiveState", 0);
}
// 假设这是启用对象的回调
public void EnableGameObject()
{
// 启用游戏对象
MyGameObject.SetActive(true);
// 在 PlayerPrefs 中存储游戏对象已被启用
PlayerPrefs.SetInt("MyGoActiveState", 1);
}
对于喜欢一行代码的人,也可以像这样设置活动状态,假设 0 用于指示禁用,而其他任何值都表示启用:
```csharp
MyGameObject.SetActive(PlayerPrefs.GetInt("MyGoActiveState") == 0);
英文:
Using PlayerPrefs
:
public GameObject MyGameObject;
void Start()
{
// Check on start if gameobject should be enabled or disabled
if (PlayerPrefs.GetInt("MyGoActiveState") == 0)
{
// Should be disabled
MyGameObject.SetActive(false);
}
else
{
// Should be enabled
MyGameObject.SetActive(true);
}
}
// Assuming this is your callback for disabling the object
public void DisableGameObject()
{
// Disable gameobject
MyGameObject.SetActive(false);
// Store in PlayerPrefs that gameobject is disabled
PlayerPrefs.SetInt("MyGoActiveState", 0);
}
// Assuming this is your callback for enabling the object
public void EnableGameObject()
{
// Enable gameobject
MyGameObject.SetActive(true);
// Store in PlayerPrefs that gameobject is enabled
PlayerPrefs.SetInt("MyGoActiveState", 1);
}
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:
MyGameObject.SetActive(PlayerPrefs.GetInt("MyGoActiveState") == 0);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论