Unity3D制作星露谷物语(2)

目录

制作Player

抽象单例基类


制作Player
  • 将Player各个部位分别进行绘制并且使用排序图层显示层次感。使用Sorting Group使所有身体部位作为一个整体进行渲染排序,避免出现下图这种情况。
没有Sorting Group
有Sorting Group

  •  设置SpriteRenderer的Sprite Sort Point为pivot(枢轴),设置为图片底部中心,在根据Y轴距离进行渲染时,用Sprite Sort Point作为观测点。
抽象单例基类
  • 使用泛型,是因为T是约束为派生于MonoBehaviour类,而我们单例就是需要返回这个唯一的对象,当进行类型转换时(this as T),如果T不加约束,则不能进行类型转换。

using UnityEngine;

/// <summary>
/// 抽象类,由其他类继承。
/// 泛型T,指定泛型参数T必须派生于基类MonoBehaviour。
/// </summary>
public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;

    public static T Instance
    {
        get
        {
            return instance;
        }
    }

    private void Awake()
    {
        if(instance == null)
        {
            instance = this as T; // 将SingletonMonoBehaviour类型转换为T类型。
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_71223431/article/details/134757819