【发布时间】:2019-01-16 23:19:49
【问题描述】:
我已经设法保存了 3D 对象的位置、旋转、比例、颜色和形状。但是,当我尝试加载对象时,颜色不显示;但其他一切工作正常。我尝试通过同行的建议使用“newObject.GetComponent().material.color = colorOfObject”,但编译器不喜欢这种语法。我在正确的轨道上吗?
注意:我刚刚包含了我的立方体选项代码以提供更短的代码块,但我确实有其他形状选项可供用户选择。
// Saving
if (GUI.Button(new Rect(700, 330, 50, 30), "Save"))
{
// Saving the object's color and resetting it to white
Color colorOfObject = rend.material.GetColor("_Color");
PlayerPrefs.SetFloat("rValue", colorOfObject.r);
PlayerPrefs.SetFloat("gValue", colorOfObject.g);
PlayerPrefs.SetFloat("bValue", colorOfObject.b);
rend.material.SetColor("_Color", Color.white);
}
// Loading
if (GUI.Button(new Rect(770, 330, 50, 30), "Load"))
{
GameObject newObject;
if (PlayerPrefs.GetString("Shape") == "cube")
{
newObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
newObject.AddComponent<cubeControls>();
newObject.transform.position = new Vector3(PlayerPrefs.GetFloat("xCoord"), PlayerPrefs.GetFloat("yCoord"), PlayerPrefs.GetFloat("zCoord"));
newObject.transform.rotation = Quaternion.Euler(PlayerPrefs.GetFloat("xRot"), PlayerPrefs.GetFloat("yRot"), PlayerPrefs.GetFloat("zRot"));
newObject.transform.localScale = new Vector3(PlayerPrefs.GetFloat("xScale"), PlayerPrefs.GetFloat("yScale"), PlayerPrefs.GetFloat("zScale"));
Color defaultColor = Color.white;
Color colorOfObject = new Color(PlayerPrefs.GetFloat("rValue", defaultColor.r), PlayerPrefs.GetFloat("gValue", defaultColor.g), PlayerPrefs.GetFloat("bValue", defaultColor.b));
//rend.material.SetColor("_Color", colorOfObject);
newObject.GetComponent().material.color = colorOfObject;
Destroy(gameObject);
}
【问题讨论】:
-
能否包含“rend”变量类型?您还确定这不是空/未定义吗?您的代码看起来不错,正如您所说,应该可以正常工作。我唯一的建议是查看 Unity 文档:docs.unity3d.com/ScriptReference/Material.GetColor.html 如您所见,您可以访问颜色调用 material.color (docs.unity3d.com/ScriptReference/Material-color.html)。
-
是的,我会继续编辑问题。
-
Unity API 中没有采用 0 个参数的
GetComponent()重载。这是您自己实现的方法吗?否则,您将缺少给它一个您想要获得的组件类型,例如GetComponent(typeof(Renderer))或GetComponent<Renderer>()
标签: c# unity3d colors save load