Unity中,需主动放置到场景中的单例

2023-07-06  本文已影响0人  全新的饭

如与当前场景逻辑强相关的光效、音效的配置和播放的控制代码。

限制场景中最多只能存在1个:第一次调用时,判断场景中是否至少存在1个,若存在多个,则保留1个,将其余的删除。

实际使用时,若不存在,可通过获取配置的方式主动创建1个(如实例化预制体的方式)

示意代码:MainGamePlayEffectCtr.cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
///  单例,需主动放置到场景中(因需要在其上配置光效资源)
/// </summary>
public class MainGamePlayEffectCtr : MonoBehaviour
{
    // todo: 一些光效预制体或一个光效配置文件

    private static MainGamePlayEffectCtr _instance;
    public static MainGamePlayEffectCtr Instance
    {
        get
        {
            if (_instance == null)
            {
                var allInstances = FindObjectsOfType<MainGamePlayEffectCtr>();
                if (allInstances.Length > 0)
                {
                    for (int i = allInstances.Length - 1; i >= 0; i--)
                    {
                        if (i == 0)
                        {
                            _instance = allInstances[i];
                            _instance.Init();
                        }
                        else
                        {
                            Destroy(allInstances[i]);
                        }
                    }
                }
                else
                {
                    Debug.Log("获取MainGamePlayEffectCtr失败!需手动在场景中放置1个!!");
                }
            }
            return _instance;
        }
    }

    private void OnDestroy()
    {
        MyDestroy();
    }

    public void Init()
    {
    }

    public void MyDestroy()
    {

    }

    // todo:若干个播放具体光效的方法(实际内部再调用EffectSys播放光效),在游戏各处调用。
}
上一篇 下一篇

猜你喜欢

热点阅读