I have two lists in unity first is List<GameObject> objList
, second is List<Animator> animList
. So I need somehow to link first object from GameObject list with first animation from Animator list, second with second and so on. How can I do this?
CodePudding user response:
The easier way is to make a class that have the both fields and make a list with this custom class. If this can't happen you don't have a "proper built-in" way to link one to another, unless you use a dictionary, you'll need to make sure that every time you access your first value in list A you will also access first item on list B
CodePudding user response:
Well are the GameObject
s of the first list the same once the Animator
components are attached to?
In this case you really only need the animList
and whenever you access an item you already have the Animator.gameObject
reference anyway.
var obj = animList[0].gameObject;
the other way round would be also possible though of course a bit more expensive if nowhere cached
var anim = objList[0].GetComponent<Animator>();
here you could have more flexibility with the relation ship by e.g. using GetComponentInChildren
if you know that it is not exactly on this object but a child.
Otherwise I would just have a class
[Serializable]
public class AnimatorObjectPair
{
public Animator animator;
public GameObject gameObject;
}
and then only store a list of
public List<AnimatorObjectPair> animatorObjectPairs;
and populate that one instead of the individual lists so you always access both references together.