• Unity中的简单数据存储办法


    这段代码演示了Unity中的简单数据存储办法 

    当涉及到不同类型的存储时,下面是一些示例代码来演示在Unity中如何使用不同的存储方法:

    1. 临时存储示例代码(内存变量):

    ```csharp
    // 定义一个静态变量来存储临时计分
    public static int score = 0;

    // 在某个事件触发时更新计分
    public void UpdateScore()
    {
        score += 10;
        Debug.Log("Score: " + score);
    }
    ```

    在上述示例中,我们使用一个静态变量 `score` 来存储临时计分。当某个事件触发时,我们可以通过增加10来更新计分,并在控制台中打印出计分。

    2. 本地存储示例代码(PlayerPrefs):

    ```csharp
    // 存储玩家姓名
    string playerName = "Tom";
    PlayerPrefs.SetString("PlayerName", playerName);

    // 获取存储的玩家姓名
    string savedName = PlayerPrefs.GetString("PlayerName");
    Debug.Log("Player Name: " + savedName);
    ```

    在上述示例中,我们使用PlayerPrefs来存储和获取玩家姓名。首先,我们使用 `SetString` 方法将玩家姓名存储为键值对,然后使用 `GetString` 方法获取存储的玩家姓名,并在控制台中打印出来。

    3. 本地存储示例代码(文件操作):

    ```csharp
    // 写入数据到文件
    string data = "Hello, World!";
    string filePath = Application.persistentDataPath + "/data.txt";
    File.WriteAllText(filePath, data);

    // 从文件中读取数据
    string readData = File.ReadAllText(filePath);
    Debug.Log("Data from file: " + readData);
    ``

    `Application.persistentDataPath默认是本地路径的C:/Users/leo/AppData/LocalLow/DefaultCompany/项目名

    在上述示例中,我们使用 `WriteAllText` 方法将字符串数据写入到本地文件。首先,我们定义一个字符串数据 `data` 和一个文件路径 `filePath`,然后调用 `WriteAllText` 方法将数据写入到指定的文件中。接下来,我们使用 `ReadAllText` 方法从文件中读取数据,并在控制台中打印出来。

    这些示例代码展示了临时存储和本地存储的两种方法,其中临时存储使用内存变量示例,而本地存储使用PlayerPrefs和文件操作示例。

    请注意,在实际开发中,你可能需要根据具体需求来适应代码,比如添加错误处理、数据格式转换等。此外,对于更复杂的本地存储需求,如存储大量数据或复杂数据结构,你可以考虑使用SQLite数据库或其他适合的方法来进行存储和访问操作。

    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using System.IO;
    4. using UnityEngine;
    5. using UnityEngine.SceneManagement;
    6. public class FileSave : MonoBehaviour
    7. {
    8. // Start is called before the first frame update
    9. void Start()
    10. {
    11. // 存储玩家姓名
    12. string playerName = "Tom";
    13. PlayerPrefs.SetString("PlayerName", playerName);
    14. // 获取存储的玩家姓名
    15. string savedName = PlayerPrefs.GetString("PlayerName");
    16. Debug.Log("Player Name: " + savedName);
    17. // 写入数据到文件
    18. string data = "Hello, World!";
    19. string filePath = Application.persistentDataPath + "/leo.txt";
    20. File.WriteAllText(filePath, data);
    21. Debug.Log(Application.persistentDataPath);
    22. // 从文件中读取数据
    23. string readData = File.ReadAllText(filePath);
    24. Debug.Log("Data from file: " + readData);
    25. SceneManager.LoadScene("leo02");//根据名字加载其他场景
    26. }
    27. // Update is called once per frame
    28. void Update()
    29. {
    30. }
    31. }

  • 相关阅读:
    【没用的小知识又增加了--CCS】
    MacOS设置JAVA_HOME环境变量
    [mockjs]Mock使用过程中的坑
    剑指offer-高质量的代码
    项目管理具体是做什么的?
    c++ 沉思录笔记——句柄(第一部分)
    Java专栏目录
    RabbitMQ 面试题及答案整理,最新面试题
    html表格标签的学习,什么是html的表格标签
    ubuntu20.04运用startup application开机自启动python程序
  • 原文地址:https://blog.csdn.net/leoysq/article/details/132998311