- Home /
how can I print to text the number of an int as well as the name of the int.
I am using a point system that has categories of points. I am looking for a way to access both the value of an int and the name of the int to be printed on what will ultimately be a "high score" page. Not sure if I am approaching with the right angle on this problem.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Int_SortScript : MonoBehaviour
{
public Text Project;
public int junk;
public int trash;
public int waste;
public int prize;
public int PrintMax;
public List<int> PointList = new List<int>();
int GetMax()
{
PointList.Sort();
int max = PointList[PointList.Count - 1];
return max;
}
void Start()
{
PointList.Add(junk);
PointList.Add(trash);
PointList.Add(waste);
PointList.Add(prize);
}
void Update()
{
PrintMax = GetMax();
Project.text = PrintMax.ToString();
}
}
Answer by Hellium · Feb 09, 2019 at 10:42 AM
Once you put the integers in the array/list, you can't retrieve its name anymore.
Try the following codes:
public class Int_SortScript : MonoBehaviour
{
public Text Project;
public int junk;
public int trash;
public int waste;
public int prize;
private string GetMax()
{
if( junk == Mathf.Max( junk, trash, waste, prize ) ) return junk + " " + nameof( junk ) ;
if( trash == Mathf.Max( junk, trash, waste, prize ) ) return trash + " " + nameof( trash ) ;
if( waste == Mathf.Max( junk, trash, waste, prize ) ) return waste + " " + nameof( waste ) ;
if( prize == Mathf.Max( junk, trash, waste, prize ) ) return prize + " " + nameof( prize ) ;
}
void Update()
{
Project.text = GetMax();
}
}
public class Int_SortScript : MonoBehaviour
{
public Text Project;
public int junk;
public int trash;
public int waste;
public int prize;
private static Dictionary<string, int> values = new Dictionary<string, int>();
private string GetMax()
{
values.Clear();
values.Add( nameof( junk ), junk ) ;
values.Add( nameof( trash ), trash ) ;
values.Add( nameof( waste ), waste ) ;
values.Add( nameof( prize ), prize ) ;
int max = -1;
string maxName = null ;
foreach( KeyValuePair<string, int> v in values )
{
if( v.Value > max )
{
max = v.Value;
maxName = v.Key;
}
}
return max + " " + maxName ;
}
void Update()
{
Project.text = GetMax();
}
}
Great! Thanks for the reply! The first one worked like a charm once I returned getmax. I would like the second one to work because that layout works for me better. I would then be able to add more ints if need be in the future. Its co$$anonymous$$g up with a missing return of a object reference which I don't understand. Would you be able to explain that too me?
$$anonymous$$y bad, I fixed the code (removed static
keyword + adding type to $$anonymous$$eyValuePair
)
Oh! that makes sense. Thank you. this works. I understand.