The error "NullReferenceException: Object reference not set to an instance of an object" typically occurs when you try to access a member on a null object. In your case, it seems that skeletonGraphic.AnimationState is null. This can happen if the SkeletonGraphic component is not properly initialized.
To resolve this issue, ensure that the SkeletonGraphic component is properly initialized before you attempt to set an animation. You can do this by calling the Initialize method on the SkeletonGraphic component. Here is an updated version of your script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Spine.Unity;
public class PlayerTopMenuController : MonoBehaviour
{
[SerializeField] private AnimationReferenceAsset addLiveAnimation, lostLiveAnimation;
private SkeletonGraphic skeletonGraphic;
void Start()
{
skeletonGraphic = GetComponent<SkeletonGraphic>();
skeletonGraphic.Initialize(false); // Ensure the SkeletonGraphic is initialized
UpdateLivesCount();
}
private void OnEnable()
{
GameActions.onPlayerLivesChanged += UpdateLivesCount;
}
private void OnDisable()
{
GameActions.onPlayerLivesChanged -= UpdateLivesCount;
}
public void UpdateLivesCount()
{
PlayAnimations();
}
// Play animations
private void PlayAnimations()
{
SetAnimation(addLiveAnimation, true, 1f);
}
public void SetAnimation(AnimationReferenceAsset animation, bool loop, float timeScale)
{
Debug.Log(animation.name);
if (animation == null) Debug.Log("Animation is null");
skeletonGraphic.AnimationState.SetAnimation(0, animation, loop); // NullReferenceException: Object reference not set to an instance of an object
}
}
Make sure that the SkeletonGraphic component is properly initialized by calling skeletonGraphic.Initialize(false); in the Start method. This should resolve the NullReferenceException error.
Additionally, ensure that your AnimationReferenceAsset fields (addLiveAnimation and lostLiveAnimation) are properly assigned in the Unity Inspector.