我有一个使用 DoTween 为窗口及其元素设置动画的脚本。但是控制台有一个我不明白的错误:
UnityException:不允许从 MonoBehaviour 构造函数(或实例字段初始值设定项)调用 get_isPlaying,请改为在 Awake 或 Start 中调用它。从游戏对象“Button(Legacy)”上的 MonoBehaviour“FadePanel”调用。有关详细信息,请参阅 Unity 手册中的“脚本序列化”页面。 DG.Tweening.DOTween.InitCheck () (位于 D:/DG/_Develop/__UNITY_ASSETS/_Demigiant/__DOTween/_DOTween.Assembly/DOTween/DOTween.cs:1128) DG.Tweening.DOTween.Sequence () (位于D:/DG/_Develop/__UNITY_ASSETS/_Demigiant/__DOTween/_DOTween.Assembly/DOTween/DOTween.cs:732) FadePanel..ctor () (位于 Assets/Assets1/scripts/FadePanel.cs:21)
---------------->
脚本本身:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class FadePanel : MonoBehaviour
{
public CanvasGroup alfaGroup;
public RectTransform BuyPanel;
private RectTransform shopButt;
Vector2 TargetPos;
Vector2 StartPos;
Vector2 targBut;
public List<RectTransform> tranf = new List<RectTransform>();
private bool isOpen = false;
Sequence anim = DOTween.Sequence();
private void Awake()
{
TargetPos = BuyPanel.transform.position;
StartPos = new Vector2(-Screen.width / 2, StartPos.x);
targBut = new Vector2(90, 177);
}
private void OnMouseDown()
{
if (!isOpen)
{
isOpen = true;
anim
.Append(BuyPanel.DOAnchorPos(TargetPos, 1f).From(StartPos))
.Join(alfaGroup.DOFade(1, 1f).From(0))
.Join(shopButt.DOAnchorPos(targBut, 1f).From(shopButt.position));
IconsUp();
}
else
{
anim
.Append(alfaGroup.DOFade(0, 1f).From(1))
.Join(shopButt.DOAnchorPos(shopButt.position, 1f).From(targBut));
}
}
private void IconsUp()
{
for (int i = 0; i < tranf.Count; i++)
{
anim
.Append(tranf[i].DOScale(1, 0.5f).From(0));
}
}
}
重点就在这一行,anim 被初始化:
实际上,这意味着将在执行此初始化的地方创建一个隐式(隐藏)构造函数。由于 Unity 不允许在从 MonoBehaviour 派生的类中创建自定义构造函数,因此您会收到错误。
尝试将动画初始化移至 Awake: