Unity_飞机大战_防止单例随场景销毁和跨场景两个物体脚本问题_自动加载物体挂载脚本的两种方式

防止单例随场景销毁和跨场景两个物体脚本问题

通过泛型封装单例类 

NormalSingleton.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//标准单例类
public class NormalSingleton<T> where T : class, new()
{
    private static T _single;

    public static T Singel
    {
        get
        {
            if (_single == null)
            {
                T t = new T();
                if (t is MonoBehaviour)
                {
                    Debug.LogError("Mono类请使用MonoSingleTon!");
                    return null;
                }

                _single = t;
            }

            return _single;
        }
    }
}
MonoSingleton.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//Mono单例类
public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _singleton;

    public static T SingleTon
    {
        get
        {
            if (_singleton == null)
            {
                _singleton = FindObjectOfType<T>();
                if (_singleton == null)
                {
                    Debug.LogError("场景中未找到类的对象,类名为:"+typeof(T).Name);
                }
            }
            return _singleton;
        }
    }

    private void Awake()
    {
        if (_singleton == null)
        {
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

通过物体路径 自动挂载脚本(游戏预制物体名字 和 脚本名字得一样)(方式一) 

ILoader接口 给ResourceLoder 和 ABLoader实现

ILoader.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface ILoader 
{
    /// <summary>
    /// Resource方法加载物体
    /// </summary>
    /// <param name="path">加载物体的路径</param>
    /// <param name="parent">指定父物体</param>
    /// <returns></returns>
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值