Cos*_*ove 6 c# formatting unity-game-engine
我正在使用Unity制作一个"增量游戏",也称为"空闲游戏",我正在尝试格式化大数字.例如,当gold
说到1000或更多时,它将显示为Gold: 1k
而不是Gold: 1000
.
using UnityEngine;
using System.Collections;
public class Click : MonoBehaviour {
public UnityEngine.UI.Text GoldDisplay;
public UnityEngine.UI.Text GPC;
public double gold = 0.0;
public int gpc = 1;
void Update(){
GoldDisplay.text = "Gold: " + gold.ToString ("#,#");
//Following is attempt at changing 10,000,000 to 10.0M
if (gold >= 10000000) {
GoldDisplay.text = "Gold: " + gold.ToString ("#,#M");
}
GPC.text = "GPC: " + gpc;
}
public void Clicked(){
gold += gpc;
}
}
Run Code Online (Sandbox Code Playgroud)
我在网上搜索时尝试了其他的例子,这是从哪里来的gold.ToString ("#,#");
,但是没有一个有效.
轻微重构:
public static string KMBMaker( double num )
{
double numStr;
string suffix;
if( num < 1000d )
{
numStr = num;
suffix = "";
}
else if( num < 1000000d )
{
numStr = num/1000d;
suffix = "K";
}
else if( num < 1000000000d )
{
numStr = num/1000000d;
suffix = "M";
}
else
{
numStr = num/1000000000d;
suffix = "B";
}
return numStr.ToString() + suffix;
}
Run Code Online (Sandbox Code Playgroud)
使用:
GoldDisplay.text = KMBMaker(gold);
Run Code Online (Sandbox Code Playgroud)
变化:
double
常量我的项目中正在使用这个方法,你也可以使用。也许有更好的方法,我不知道。
public void KMBMaker( Text txt, double num )
{
if( num < 1000 )
{
double numStr = num;
txt.text = numStr.ToString() + "";
}
else if( num < 1000000 )
{
double numStr = num/1000;
txt.text = numStr.ToString() + "K";
}
else if( num < 1000000000 )
{
double numStr = num/1000000;
txt.text = numStr.ToString() + "M";
}
else
{
double numStr = num/1000000000;
txt.text = numStr.ToString() + "B";
}
}
Run Code Online (Sandbox Code Playgroud)
并在更新中使用此方法,如下所示。
void Update()
{
KMBMaker( GoldDisplay.text, gold );
}
Run Code Online (Sandbox Code Playgroud)