当用户想OnGUI()函数输入信息时输入的事string类型,但是在常用的Vector3()函数中要求必须是int或者float类型,如果是int还好说,可以直接使用convert().但是当用户输入float的时候就会报错,所以此时最好使用parse()来实现类型的强制转换,parse()和GUI的结合的使用又有很多要求,类型转换是最好直接在Vector3(),函数的参数部分进行。例如Vector3(float.Parse(x), float.Parse(y), float.Parse(z));
下面是小编自己的完成的实例。
程序要求:
1 在程序用行是用户通过UI界面输入太阳的圆心坐标。
2 用户通过UI界面输入旋转半径,实现地球绕太阳旋转的案例。
具体代码如下;
using UnityEngine;
using System.Collections;using System;
public class inputR : MonoBehaviour
{
private GameObject earth;//声明一个旋转的变量
private GameObject sun;//声明一个旋转中心的变量
private string radius;//定义一个输入半径的变量
private string info;
private string x,y,z;//定义一个输入坐标的变量
private bool is_clicked = false;//设置一个标志位用于监控处理异常
void Start()
{
x = "";
y = "";
z = "";
radius = "";
}
void Update()
{
if (is_clicked)
{
earth.transform.RotateAround(sun.transform.position, Vector3.up, 1f);//使求绕旋转中心物体旋转
}
}
void OnGUI()
{
//用户输入x坐标
GUI.Label(new Rect(20, 50, 300, 20), "x坐标: ");
x = GUI.TextField(new Rect(80, 50, 50, 20), x, 15);//15为最大字符串长度
//用户输入y坐标
GUI.Label(new Rect(20, 80, 300, 20), "y坐标:");
y = GUI.TextField(new Rect(80, 80, 50, 20), y, 15);//15为最大字符串长度
//用户输入z坐标
GUI.Label(new Rect(20, 100, 300, 20), "z坐标:");
z = GUI.TextField(new Rect(80, 100, 50, 20), z, 15);//15为最大字符串长度
//用户输入半径
GUI.Label(new Rect(20, 20, 300, 20), "请输入旋转半径:");
radius = GUI.TextField(new Rect(130, 20, 50, 20), radius, 15);//15为最大字符串长度
//显示输入的是否正确
GUI.Label(new Rect(20, 100, 100, 20), info);
if (GUI.Button(new Rect(130, 200, 50, 20), "确定"))
{
//判断输入的半径是否符合要求
if (float.Parse(radius) > 0)
{
GameObject Sun = GameObject.CreatePrimitive(PrimitiveType.Sphere);//创建一个旋转的球体
GameObject Earth = GameObject.CreatePrimitive(PrimitiveType.Sphere);//创建一个被旋转的球体
Sun.name = "Sun";//重命名球体
Earth.name = "Earth";
earth = GameObject.Find("Earth");//找到球体,用于下一步的旋转
sun = GameObject.Find("Sun");
Sun.transform.position = new Vector3(float.Parse(x), float.Parse(y), float.Parse(z));//获取用户输入的旋转中心坐标
Sun.transform.localScale = new Vector3(2, 2, 2);//放大旋转中心球体
earth.transform.position = new Vector3(float.Parse(radius), float.Parse(y), float.Parse(radius));//获取旋转球的坐标
is_clicked = true;
}
else
{
info = "半径不能小于零";
}
}
}
}