【发布时间】:2019-01-13 20:30:13
【问题描述】:
我已经实现了用户可以选择自定义 3D 对象的所有选项,并添加了一些 GUI 按钮来改进我的旧代码并提高可用性。但是我在弄清楚如何保存和加载游戏对象时遇到了一些麻烦。
我读过关于序列化的文章,也看到有人提到 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"))
{
}
}
}
【问题讨论】:
标签: c# object unity3d save load