using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test1 : MonoBehaviour {
string str1 = "12.222";
string str2 = "123";
string str3 = "abc";
float a;
int b;
void Start () {
if (float.TryParse(str1,out a))
{
a = float.Parse(str1);
Debug.Log(a + 12);
}
else
{
Debug.Log("无法转换");
}
//float无法转换为int
if (int.TryParse(str1, out b))
{
b = int.Parse(str1);
Debug.Log(a + 12);
}
else
{
Debug.Log("无法转换");
}
//int可以转成float
if (float.TryParse(str2, out a))
{
a = float.Parse(str2);
Debug.Log(a + 12);
}
else
{
Debug.Log("无法转换");
}
//字符串无法传转换为int 和 float
if (float.TryParse(str3, out a))
{
a = float.Parse(str3);
Debug.Log(a + 12);
}
else
{
Debug.Log("无法转换");
}
if (int.TryParse(str3, out b))
{
b = int.Parse(str3);
Debug.Log(a + 12);
}
else
{
Debug.Log("无法转换");
}
//另一种方式
Debug.Log(Convert.ToSingle(str1));
Debug.Log(Convert.ToInt32(str2));
}
}
结果: