我试图考虑一个通用方法,该方法将对当前代码有所帮助。这不是问题,我只是想知道是否可以这样做。我有两种基本上可以完成相同操作的方法,但是它们使用不同的转换。我正在考虑如何实现通用方法来编写此代码。
private void ImagePieceClickEvent(GameObject target, MouseEventType type)
{
if (type == MouseEventType.CLICK && canClick)
{
//imagePiceTarget has Transform type
if (imagePieceTarget != null && imagePieceTarget != target.transform)
imagePieceTarget.GetComponent<SpriteRenderer>().DOFade(0.7f, 0.2f);
if (imagePieceTarget == target.transform)
{
imagePieceTarget.GetComponent<SpriteRenderer>().DOFade(0.7f, 0.2f);
imagePieceTarget = null;
}
else
{
imagePieceTarget = target.transform;
imagePieceTarget.GetComponent<SpriteRenderer>().DOFade(1f, 0.2f).OnComplete(CheckAnswer);
}
}
}
private void ClonePieceClickEvent(GameObject target, MouseEventType type)
{
if (type == MouseEventType.CLICK && canClick)
{
//clonePieceTarget has Transform type
if (clonePieceTarget != null && clonePieceTarget != target.transform)
clonePieceTarget.transform.DOScale(0.7f, 0.2f);
if (clonePieceTarget == target.transform)
{
clonePieceTarget.transform.DOScale(0.7f, 0.2f);
clonePieceTarget = null;
}
else
{
clonePieceTarget = target.transform;
clonePieceTarget.transform.DOScale(1f, 0.2f).OnComplete(CheckAnswer);
}
}
}
所有处于IF条件的代码都将以通用方法实现,然后调用它。为什么我不能这样做,因为第一种方法调用.DOFade()方法,而第二种方法调用DOScale()。 我想知道是否可以使用通用方法进行简化,谢谢。
答案 0 :(得分:1)
我会使用System.Action
和ref
keyword来解决您的问题。
尝试以下操作:
private void PieceClickEvent(Transform target, MouseEventType type, ref Transform pieceTarget, System.Action<Transform> onFocus, System.Action<Transform> onBlur )
{
if (type == MouseEventType.CLICK && canClick)
{
if (pieceTarget != null && pieceTarget != target && onBlur != null)
{
onBlur( pieceTarget ) ;
}
if (imagePieceTarget == target.transform)
{
if( onBlur != null )
onBlur( pieceTarget ) ;
pieceTarget = null;
}
else
{
pieceTarget = target;
if( onFocus != null )
onFocus( pieceTarget ) ;
}
}
}
// ...
PieceClickEvent(
target.transform,
type,
ref imagePieceTarget,
t => t.GetComponent<SpriteRenderer>().DOFade(1f, 0.2f).OnComplete(CheckAnswer),
t => t.GetComponent<SpriteRenderer>().DOFade(0.7f, 0.2f)
);
PieceClickEvent(
target.transform,
type,
ref clonePieceTarget,
t => t.DOScale(1f, 0.2f).OnComplete(CheckAnswer),
t => t.DOScale(0.7f, 0.2f)
);