Question by
Awsz · Dec 04, 2016 at 09:19 PM ·
c#percentage
Percentage calculation
Hi, im working on a project.
I'm having an issue with a script calculating the percentage. I kind of works, but not really, if you understand. here is my script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class spawner : MonoBehaviour {
public Transform LeftSpawn;
public Transform RightSpawn;
public GameObject LeftCube;
public GameObject RightCube;
public Text LeftText;
public Text RightText;
public int LeftCount;
public int RightCount;
public int TotalCount;
public float LeftFraction;
public float RightFraction;
public float LeftPercentage;
public float RightPercentage;
// Use this for initialization
void Start () {
LeftCount = 0;
RightCount = 0;
TotalCount = 0;
}
// Update is called once per frame
void Update () {
// if both right and left have at least 1 cube each
if (LeftCount != 0 && RightCount != 0) {
//the total amount of cubes
TotalCount = LeftCount + RightCount;
// how much out of the total amount is left?
LeftFraction = TotalCount / LeftCount;
//how much out of the total amount is right?
RightFraction = TotalCount / RightCount;
//calculate how much (in percentage) there are left cubes
LeftPercentage = 100 / LeftFraction;
// same with right cubes
RightPercentage = 100 / RightFraction;
// show the percentage
LeftText.text = LeftPercentage.ToString () + "%";
//ditto
RightText.text = RightPercentage.ToString () + "%";
}
// if "a" is pressed
if (Input.GetKeyDown (KeyCode.A)) {
// spawn cube at designated transform
Instantiate (LeftCube, LeftSpawn);
// add one to leftcount and totalcount, confirm everything happenned
LeftCount += 1;
TotalCount += 1;
Debug.Log ("done");
}
//if "d" is pressed
if (Input.GetKeyDown (KeyCode.D)) {
//spawn cube at designated transform
Instantiate (RightCube, RightSpawn);
// add one to rightcount and total count, confirm it happenned
RightCount += 1;
TotalCount += 1;
Debug.Log ("done");
}
}
}
here is my script in action:
here, the leftcube to rightcube ratio is 5:2
the script only works if both sides have an equal number squares, putting "50%" on each side.
Can someone help me?
unity.png
(104.0 kB)
Comment
@Awsz Hi I'm actually trying to accomplish a similar thing to you right now, by any chance could you help me?
Answer by hexagonius · Dec 04, 2016 at 09:28 PM
what about this equation:
text = LeftCount / TotalCount * 100;
same for right