How to get specific instance of component in SerializeField if there are several components of the same type on the same object?

I have this component that I use to control some kind of animation. I can have several components of this class on the same object - for example one component controls scale animation and other controls some kind of movement.

public abstract class Showable : MonoBehaviour
{
	[SerializeField] public float defaultDuration = 0.2f;

	public abstract void Show(float t, Action callback = null);
	public abstract void Hide(float t, Action callback = null);
	public abstract void HideImmediatly(Action callback = null);

	public virtual void Show(Action callback = null) => Show(defaultDuration, callback);
	public virtual void Hide(Action callback = null) => Hide(defaultDuration, callback);

	public void ShowFromHiddenState(float t, Action callback = null)
	{
		HideImmediatly(() => Show(t, callback));
	}

	public void ShowFromHiddenState(Action callback = null)
	{
		HideImmediatly(() => Show(defaultDuration, callback));
	}
}

I also created this MultipleAnimations component to combine several animations into one Showable.

public class MultipleAnimations : Showable
{
	[SerializeField] private List<Showable> animations;

	public override void Show(float t, Action callback = null)
	{
		animations.ForEach(x => x.Show(t));
		Scheduler.Delay(callback, t);
	}

	public override void Hide(float t, Action callback = null)
	{
		animations.ForEach(x => x.Hide(t));
		Scheduler.Delay(callback, t);
	}

	public override void HideImmediatly(Action callback = null)
	{
		animations.ForEach(x => x.HideImmediatly());
		callback?.Invoke();
	}
}

The problem is that I can’t drag and drop several animations into this list, because I will just add the same component (I assume it the top component in the hierarchy).

You would need to drag the specific components themselves into the collection, via dragging their component headers.

You might need to Right-Click β†’ Properties on the game object to open up a mini-inspector to make it easier to drag the components.

Mind you, this would be an instance where serialising these as plain C# classes with polymorphism using SerializeReference would be more straight-forward, granted you have the inspector support. I have an example here: abstract SkillList that can be edited in Inspector - #15 by spiney199

1 Like