简体   繁体   English

如何保存和加载用户创建的游戏对象?

[英]How can I save and load the gameObject that the user creates?

I've implemented all the options that the user can choose to customize a 3D object, as well as adding some GUI buttons to improve my old code and to make usability better.我已经实现了用户可以选择的所有选项来自定义 3D 对象,并添加了一些 GUI 按钮来改进我的旧代码并提高可用性。 But I'm having some trouble figuring out how to save and load a gameObject.但是我在弄清楚如何保存和加载游戏对象时遇到了一些麻烦。

I've read about serialization and I've seen some people mention PlayerPrefs, but I'm still having trouble understanding how to use that with an object.我读过有关序列化的文章,也看到有人提到过 PlayerPrefs,但我仍然无法理解如何将其与对象一起使用。

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;

 public class cubeControls : MonoBehaviour
 {
     // Constants for object rotation
     public float moveSpeed = 80.0F;
     public float turnSpeed = 100.0F;

     // Initial scale of the original cube
     public static Vector3 initscale = Vector3.one;

     // Start is called before the first frame update
     void Start()
     {
     }

     // Update is called once per frame
     void Update()
     {
         // Changing the position of the object

         // Moving the object right
         if (Input.GetKey(KeyCode.D))
         {
             transform.Translate(Vector3.right * moveSpeed * Time.deltaTime);
     }

         // Moving the object left
         if (Input.GetKey(KeyCode.A))
         {
             transform.Translate(Vector3.left * moveSpeed * Time.deltaTime);
     }

         // Changing the rotation of the object

         // Rotating the cube to the right
         if (Input.GetKey(KeyCode.RightArrow))
         {
             transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);
         }

         // Rotating the cube to the left
         if (Input.GetKey(KeyCode.LeftArrow))
         {
             transform.Rotate(Vector3.down, turnSpeed * Time.deltaTime);
         }

         // Saving the current rendered material
         Renderer rend = GetComponent<Renderer>();

         // Changing the scale of the object

         // Double the size of the cube
         if (Input.GetKeyDown(KeyCode.Alpha2))
         {
             transform.localScale += new Vector3(2F, 2F, 2F);
         }

         // Changing the color via key presses

         if (Input.GetKeyDown(KeyCode.R))
         {
             rend.material.SetColor("_Color", Color.red);
         }
     }

     // To add button elements to the visual interface
     void OnGUI() 
     {
         // Changing to cylinder
         if (GUI.Button(new Rect(50, 90, 100, 40), "Cylinder"))
         {
             GameObject newCylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
             newCylinder.AddComponent<cubeControls>();
             Destroy(gameObject);
         }

         // Saving
         if (GUI.Button(new Rect(700, 330, 50, 30), "Save"))
         {
         }

         // Loading
         if (GUI.Button(new Rect(770, 330, 50, 30), "Load"))
         {
         }
     }
 }

You cannot save Gameobjects.您无法保存游戏对象。 Only thing you save is details of the game object.您唯一保存的是游戏对象的详细信息。 Take for example if you have 3D cube with some particle effects first you save the required values of the cube like Position, Rotation, Scale, Color and other necessary elements(particle emitter values which needs to be change).举个例子,如果你有一些粒子效果的 3D 立方体,你首先保存立方体所需的值,如位置、旋转、缩放、颜色和其他必要的元素(需要更改的粒子发射器值)。 Even in serialisation you will not be able to save Vector3 as it is a struct and have to write your own serialiser for vectors.即使在序列化中,您也无法保存 Vector3,因为它是一个结构体,并且必须为向量编写自己的序列化程序。 Basically in short what you save in values required for your gameobjects to work and other behavioral characteristics which required custom inputs from user/ other system.基本上简而言之,您保存了游戏对象工作所需的值以及需要来自用户/其他系统的自定义输入的其他行为特征。 Think of it as way to rebuild your objects to the state where you left off by saving and loading states of variables which affects your objects.将其视为通过保存和加载影响对象的变量状态来将对象重建到中断状态的方法。

Unity saves are of two types Unity 保存有两种类型

1) Player prefs : Using player prefs you will be able to save only one value at a time in the field. 1)玩家偏好:使用玩家偏好,您一次只能在现场保存一个值。 Usually one of the three:通常是以下三种之一:

  • Float漂浮
  • Int整数
  • String细绳

You usually save tokens and other small values which wont require large files您通常会保存不需要大文件的令牌和其他小值

2) Serialized Game Data : Here you save the large data sets & classes like PlayerInfo, Custom changes to scene in a serialized files. 2) 序列化游戏数据:在这里,您将大型数据集和类(如 PlayerInfo、对场景的自定义更改)保存在序列化文件中。

I believe what you are looking for is the second one.我相信你正在寻找的是第二个。 So instead of looking for all the examples and getting confused what you can really start with is saving/loading a cube values(position maybe? or anything which you are modifying at runtime) in a file.因此,与其查找所有示例并弄糊涂,您真正可以开始的是在文件中保存/加载多维数据集值(可能是位置?或您在运行时修改的任何内容)。 And gradually you can shift to serializer.逐渐地,您可以转向序列化程序。

You can check on this following links to help you further understand.您可以查看以下链接以帮助您进一步了解。

Reference 参考

Save/Load Data using simple BinaryFormatter 使用简单的 BinaryFormatter 保存/加载数据

XML serialiser XML 序列化程序


This save snippet is from simple binary formattor link, which saves integer lists of some types & user score.这个保存片段来自简单的二进制格式器链接,它保存了某些类型和用户分数的整数列表。

[System.Serializable]
public class Save
{
  public List<int> livingTargetPositions = new List<int>();
  public List<int> livingTargetsTypes = new List<int>();

  public int hits = 0;
  public int shots = 0;
}

private Save CreateSaveGameObject()
{
  Save save = new Save();
  int i = 0;
  foreach (GameObject targetGameObject in targets)
  {
    Target target = targetGameObject.GetComponent<Target>();
    if (target.activeRobot != null)
    {
      save.livingTargetPositions.Add(target.position);
      save.livingTargetsTypes.Add((int)target.activeRobot.GetComponent<Robot>().type);
      i++;
    }
  }

  save.hits = hits;
  save.shots = shots;

  return save;
}

public void SaveGame()
{
  // 1
  Save save = CreateSaveGameObject();

  // 2
  BinaryFormatter bf = new BinaryFormatter();
  FileStream file = File.Create(Application.persistentDataPath + "/gamesave.save");
  bf.Serialize(file, save);
  file.Close();

  // 3
  hits = 0;
  shots = 0;
  shotsText.text = "Shots: " + shots;
  hitsText.text = "Hits: " + hits;

  ClearRobots();
  ClearBullets();
  Debug.Log("Game Saved");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM