Home > Net >  Unity C#: how can i return a list/array/length of the variables inside an animator component?
Unity C#: how can i return a list/array/length of the variables inside an animator component?

Time:11-10

I have an animator component with lots of different variables and within my code I often run a condition that checks if most of these valuables are false.

I'd like to speed this up by making a method that runs a for loop and returns if yes or no any of those variables are true/false but cant find anything about it online.

CodePudding user response:

Animator.parameterCount or Animator.GetParameter(int index) can fetch those, you can very easily skim through your parameters by making a for loop as such

Animator anim
for(int i = 0; i < anim.parameterCount ; i  ){anim.GetParameter(i)}

CodePudding user response:

You can do

  • Get all Animator.parameters
  • Filter out only those that are Bool parameters using Linq Where
  • Use Linq Any or Linq All according to your needs to check if one or all of these parameters fulfill a certain condition. In your case whether GetBool returns true

Something like e.g.

using System.Linq;

...

var animator = GetComponent<Animator>();
var allParameters = animator.parameters;
// Filter and get only those of type Bool
var allBoolParameters = allParameters.Where(p => p.type == AnimatorControllerParameterType.Bool);

// Check if any of them is true
var anyBoolParameterIsTrue = allBoolParameters.Any(p => animator.GetBool(p.nameHash));

// Check if All of them are true
var allBoolParametersAreTrue = allBoolParameters.All(p => animator.GetBool(p.nameHash));

Basically this somewhat equals doing something like this without Linq

var animator = GetComponent<Animator>();
var allParameters = animator.parameters;

// Filter and get only those that are of type Bool
var allBoolParameters = new List<AnimatorControllerParameter>();
foreach(var p in allParameters)
{
    if(p.type != AnimatorControllerParameterType.Bool) continue;

    allBoolParameters.Add(p);
}

// Check if any of them is true
var anyBoolParameterIsTrue = false;
foreach(var p in allBoolParameters)
{
    if(animator.GetBool(p.nameHash)) 
    {
        anyBoolParameterIsTrue = true;
        break;
    }
}

// Check if all of them are true
var allBoolParametersAreTrue = true;
foreach(var p in allBoolParameters)
{
    if(!animator.GetBool(p.nameHash)) 
    {
        allBoolParametersAreTrue = false;
        break;
    }
}
  • Related