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

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

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);

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:

确定