Hi!
I’m trying to scale gameobjects depending on their childcount using a compound rule of three. So I have a max scale (0.25) for the gameobject with the highest childcount and a min scale (0.1) for the gameobject with the lowest one, and the values I should get must be between maxScale and minScale. Let’s say that the highest childcount is 108 and the second highest is 13. The value I should get for 13 must be closer to 0.25 than to 0.1. I know I must be missing something. This is my code:
public GameObject[] goArray;
private void GetHighestChildCount ()
{
List<int> numberOfChildrenList = new List<int>();
for (int i = 0; i < goArray.Length; i++)
{
numberOfChildrenList.Add(goArray*.transform.childCount);*
}
maxNumberOfChildren = Mathf.Max(numberOfChildrenList.ToArray());
}
private void ScaleGO ()
{
float maxScale = 0.0625f;
float minScale = 0.01f;
for (int i = 0; i < goArray.Length; i++)
{
float newScale = (maxScale * minScale * goArray_.transform.childCount) / (maxNumberOfChildren * minScale);
goArray*.transform.localScale = new Vector3(newScale, newScale, newScale);*
}
}_
This line makes not too much sense:
float newScale = (maxScale * minScale * goArray_.transform.childCount) / (maxNumberOfChildren * minScale);_
Just by reduction you can completely remove minScale from your calculations since you multiply by minScale on the “top” and you also divide by minScale on the “bottom”. So this line would be similar to:
float newScale = (maxScale * minScale * goArray_.transform.childCount) / (maxNumberOfChildren * minScale);
What you actually want to do is this:
float newScale = minScale + ((maxScale - minScale) * goArray*.transform.childCount) / (maxNumberOfChildren);*
Though another probably simpler solution is to use Lerp since that’s just what Lerp does.
float newScale = Mathf.Lerp(minScale, maxScale, (float)goArray*.transform.childCount / maxNumberOfChildren);*
Even your first approach would be easier to understand to break it down into it’s parts. Specifically:
float range = maxScale - minScale;
float t = (float)goArray*.transform.childCount / maxNumberOfChildren;*
float newScale = minScale + range * t;
The same could be done with my Lerp example to make it more readable:
float t = (float)goArray*.transform.childCount / maxNumberOfChildren;*
float newScale = Mathf.Lerp(minScale, maxScale, t);
Note that the float cast is important since both arguments (childCount and maxNumberOfChildren) are integers. If you divide two integers the result is an integer as well. Since this calculation will always be a fraction between 0 and 1 it would always trucate to 0 without the cast. If you declare the “maxNumberOfChildren” variable as float instead of int you would not need the cast._