Unity 常用功能代码工具集

Unity 常用功能整理

安卓摄像头的调用请求与拍摄、截图

///
/// ———————— SakuraNeko ————————
/// 
/// 博客园:https://www.cnblogs.com/sakuraneko/
///
/// ——————————————————————— 
///
/// 使用方式:
/// 添加一个 Canvas ,并且在 Canvas 下创建一个 RawImage 为必要的组件
/// 将组件正确拖拽至脚本所需组件上
/// 打包 APK 即可测试内容

using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using System;

//设置摄像头枚举
public enum CameraType
{
    BackCamera = 0,         // 后置摄像头
    FrontCamera = 1,        // 前置摄像头
}

// 设置图片保存类型
public enum TextureType
{
    Jpg,                    // .jpg
    Png,                    // .png
}

public class OpenCamera : MonoBehaviour
{
    [Header("接受摄像机内容的图片")]
    public RawImage rawImage;
    [Header("摄像机反转按钮")]
    public Button btn_cameraType;
    [Header("拍照")]
    public Button btn_photoShoot;
    [Header("场景截图")]
    public Button btn_screenshots;

    private WebCamTexture webCamTexture;
    private int fps = 60;

    void Start()
    {
        // 按钮添加添加监听事件
        // 1、添加摄像机反转事件
        btn_cameraType?.onClick.AddListener(SelectCameraType);
        // 2、添加拍照事件
        btn_photoShoot?.onClick.AddListener(PlayPhotoShoot);
        // 3、添加截图事件
        btn_screenshots?.onClick.AddListener(PlayScreenshots);

#if UNITY_ANDROID
        filePath = "";
        string[] path = Application.persistentDataPath.Split('/');
        for (int i = 0; i < path.Length; i++)
        {
            if (path[i] == "Android")
                break;

            filePath += path[i] + "/";
        }
        filePath += "DCIM/Camera";
        //filePath = Application.streamingAssetsPath + "/sdcard/DCIM/Camera";
#endif

        Check();

        // 设置默认打开后置摄像头
        cameraType = CameraType.BackCamera;
        StartCoroutine(ToOpenCamera());
    }

    // 开启摄像头渲染
    IEnumerator ToOpenCamera()
    {
        // 获取摄像头权限
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            // 停止正在使用的摄像头
            if (webCamTexture != null)
            {
                webCamTexture.Stop();
            }

            //判断当前摄像头类型关闭当前协程切换成对应摄像头
            if (cameraType == CameraType.BackCamera)
            {
                //切换后置摄像头需要镜像回来,不然拍摄左右会颠倒
                rawImage.transform.eulerAngles = new Vector3(0, 0, 0);
            }
            else
            {
                //切换前置摄像头需要镜像,不然拍摄左右会颠倒
                rawImage.transform.eulerAngles = new Vector3(0, 180, 0);
            }

            // 判断是否有摄像头
            if (WebCamTexture.devices.Length != 0)
            {
                // 新建一个摄像头并且设置分辨率和FPS,渲染到UI上
                webCamTexture = new WebCamTexture(WebCamTexture.devices[(int)cameraType].name,
                    (int)Screen.width / 2, (int)Screen.height / 2, fps);

                // 等待摄像机响应并创建好图层
                yield return new WaitWhile(() => (webCamTexture == null));

                rawImage.texture = webCamTexture;
                webCamTexture.Play();
            }
        }
    }

    // 获取照片
    IEnumerator GetTexture(string _filePath, TextureType _type)
    {
        yield return new WaitForEndOfFrame();
        Texture2D t = new Texture2D(Screen.width, Screen.height);
        t.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);
        t.Apply();
        if (_type == TextureType.Jpg)
        {
            byte[] byt = t.EncodeToJPG();
            File.WriteAllBytes(_filePath, byt);
        }
        if (_type == TextureType.Png)
        {
            byte[] byt = t.EncodeToPNG();
            File.WriteAllBytes(_filePath, byt);
        }
        OnSaveImagesPlartform(_filePath);
        webCamTexture?.Play();
    }

    private CameraType cameraType;
    /// <summary>
    /// 摄像头方向切换
    /// </summary>
    private void SelectCameraType()
    {
        // 先关闭摄像机渲染
        StopCoroutine("ToOpenCamera");

        // 判断当前摄像头类型是前置还是后置,进行反给处理
        cameraType = cameraType == CameraType.BackCamera ? CameraType.FrontCamera : CameraType.BackCamera;

        // 开启摄像机渲染
        StartCoroutine(ToOpenCamera());
    }

    string filePath = "";
    /// <summary>
    /// 运行拍照逻辑
    /// </summary>
    private void PlayPhotoShoot()
    {
        Check();

        // 暂停摄像头渲染
        webCamTexture.Pause();

        // 进行截图拍摄
        StartCoroutine(GetTexture(string.Format("{0}/{1}.png", filePath, DateTime.Now.ToString().Replace('/', '_').Replace(':', '_')), TextureType.Png));
    }

    /// <summary>
    /// 运行截图逻辑
    /// </summary>
    private void PlayScreenshots()
    {
        Check();

        // 进行截图拍摄
        StartCoroutine(GetTexture(string.Format("{0}/{1}.png", filePath, DateTime.Now.ToString().Replace('/', '_').Replace(':', '_')), TextureType.Png));
    }

    /// <summary>
    /// 查询是否拥有相册权限
    /// </summary>
    private void Check()
    {
        Debug.Log("相册写入权限:" + UnityEngine.Android.Permission.HasUserAuthorizedPermission(UnityEngine.Android.Permission.ExternalStorageWrite) +
            "相册读取权限:" + UnityEngine.Android.Permission.HasUserAuthorizedPermission(UnityEngine.Android.Permission.ExternalStorageRead));
        if (!UnityEngine.Android.Permission.HasUserAuthorizedPermission(UnityEngine.Android.Permission.ExternalStorageWrite))
        {
            UnityEngine.Android.Permission.RequestUserPermission(UnityEngine.Android.Permission.ExternalStorageWrite);
        }
        if (!UnityEngine.Android.Permission.HasUserAuthorizedPermission(UnityEngine.Android.Permission.ExternalStorageRead))
        {
            UnityEngine.Android.Permission.RequestUserPermission(UnityEngine.Android.Permission.ExternalStorageRead);
        }
    }

    /// <summary>
    /// 刷新相册(不需要单独创建原生aar或jar)
    /// </summary>
    /// <param name="path"></param>
    private void OnSaveImagesPlartform(string filePath)
    {
#if UNITY_ANDROID
        string[] paths = new string[1] { filePath };

        using (AndroidJavaClass PlayerActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            AndroidJavaObject playerActivity = PlayerActivity.GetStatic<AndroidJavaObject>("currentActivity");
            using (AndroidJavaObject Conn = new AndroidJavaObject("android.media.MediaScannerConnection", playerActivity, null))
            {
                Conn.CallStatic("scanFile", playerActivity, paths, null, null);
            }
        }
#endif
    }
}
代码示例

 

纹理贴图压缩

///
/// ———————— SakuraNeko ————————
/// 
/// 博客园:https://www.cnblogs.com/sakuraneko/
///
/// ——————————————————————— 
///
/// 使用方式:
/// 将脚本放入项目中,编辑器窗口会有Image/ChangeFormat窗口
/// 设置好窗口的内容
/// 将资源目录下需要压缩的贴图选取后在窗口进行“开始”
/// 打包 APK 即可看到比原先包体会有变化

using UnityEngine;
using System.Collections;
using UnityEditor;
using System;
using System.Collections.Generic;
public class ChangeFormat : EditorWindow
{
    TextureImporterFormat format = TextureImporterFormat.AutomaticCompressed;
    int size = 512;
    BuildTarget buildTarget = BuildTarget.WebGL;
    bool autoSize = false;
    [MenuItem("Image/ChangeFormat")]
    static void SetReadWriteTrue()
    {
        ChangeFormat changeFormat = EditorWindow.GetWindow(typeof(ChangeFormat)) as ChangeFormat;
    }

    void OnGUI()
    {

        GUILayout.BeginHorizontal();
        GUILayout.Label("平台:");
        buildTarget = (BuildTarget)EditorGUILayout.EnumPopup(buildTarget);
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        GUILayout.Label("格式:");
        format = (TextureImporterFormat)EditorGUILayout.EnumPopup(format);
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        GUILayout.Label("贴图大小:");
        size = EditorGUILayout.IntField(size);
        GUILayout.EndHorizontal();

        //GUILayout.BeginHorizontal();
        //GUILayout.Label("使用贴图原始大小:");
        //autoSize = EditorGUILayout.Toggle(autoSize);
        //GUILayout.EndHorizontal();

        //GUILayout.BeginHorizontal();
        //GUILayout.Label("平台:");
        //platform = EditorGUILayout.TextField(platform);
        //GUILayout.EndHorizontal();

        if (GUILayout.Button("开始"))
        {
            Execute();
        }

    }


    void Execute()
    {
        Debug.LogWarning("开始");
        UnityEngine.Object[] selectedAsset = Selection.GetFiltered(typeof(Texture), SelectionMode.DeepAssets);
        int currentSize = size;


        // for (int i = 0; i < selectedAsset.Length; i++)
        // {
        //     Debug.LogError(selectedAsset[i].name);
        //     Texture2D tex = selectedAsset[i] as Texture2D;
        //     TextureImporter ti = (TextureImporter)TextureImporter.GetAtPath(AssetDatabase.GetAssetPath(tex));
        //     TextureImporterFormat format = ti.GetAutomaticFormat(buildTarget.ToString());
        //
        //     TextureImporterPlatformSettings texx = new TextureImporterPlatformSettings();
        //     texx.maxTextureSize = currentSize;
        //     texx.format = format;
        //     ti.SetPlatformTextureSettings(texx);
        //     texx.overridden = false;
        //     //texx.crunchedCompression = false;
        //     //texx.allowsAlphaSplitting = false;
        //     AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(tex));
        //     AssetDatabase.Refresh();
        // }


        for (int i = 0; i < selectedAsset.Length; i++)
        {

            Debug.LogError(selectedAsset[i].name);
            Texture2D tex = selectedAsset[i] as Texture2D;
            TextureImporter ti = (TextureImporter)TextureImporter.GetAtPath(AssetDatabase.GetAssetPath(tex));

            //  //if (autoSize) {
            //  //    currentSize = ti.maxTextureSize;
            //  //}
            //  ti.SetPlatformTextureSettings(platform, currentSize, format);

            //  TextureFormat desiredFormat; 
            //   ColorSpace colorSpace;
            //  int compressoinQuality;
            //  ti.ReadTextureImportInstructions(BuildTarget.Android, out desiredFormat, out colorSpace, out compressoinQuality);

            if (ti == null) continue;

            //TextureImporterFormat formatt = (TextureImporterFormat)Enum.Parse(typeof(TextureImporterFormat), "DXT1") ;
            TextureImporterFormat formatt = ti.GetAutomaticFormat(BuildTarget.WebGL.ToString());
            string format_str = formatt.ToString();
            Debug.LogError("format_str:" + format_str);
            if (format_str.Contains("Crunched"))//已经是压缩过的;
            {

            }
            else//没有压缩过的 todo
            {
                if (format_str.Contains("DXT1"))
                {
                    formatt = (TextureImporterFormat)Enum.Parse(typeof(TextureImporterFormat), "DXT1Crunched");
                }
                else
                {
                    formatt = (TextureImporterFormat)Enum.Parse(typeof(TextureImporterFormat), "DXT5Crunched");
                }
            }


            TextureImporterPlatformSettings texx = new TextureImporterPlatformSettings();
            //if (ti.maxTextureSize < 1024)
            //{
            //    texx.maxTextureSize = ti.maxTextureSize;
            //}
            //else
            //{
            //    texx.maxTextureSize = currentSize;
            //}
            texx.maxTextureSize = ti.maxTextureSize;
            texx.format = formatt;
            texx.overridden = false;
            ti.SetPlatformTextureSettings(texx);

            AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(tex));
            AssetDatabase.Refresh();
        }
        Debug.LogWarning("结束");
    }
}
代码示例

 

随机名字库

/// <summary>
    /// 随机获取的名字
    /// </summary>
    /// <returns></returns>
    public static string GetChinessName()
    {
        string name = "";
        string[] _crabofirstName = new string[]{
            "","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",
            "","","","","","","","","" ,"","","","","","","","","","","","","","","","","","","","","","" ,"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","" ,"","","","","","","","" ,"","","","","","","","","","","","","" ,"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","" ,"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""
           };

        string _lastName = "震南洛栩嘉光琛潇闻鹏宇斌威汉火科技梦琪忆柳之召腾飞慕青问兰尔岚元香初夏沛菡傲珊曼文乐菱痴珊恨玉惜香寒新柔语蓉海安夜蓉涵柏水桃醉蓝春语琴从彤傲晴语菱碧彤元霜怜梦紫寒妙彤曼易南莲紫翠雨寒易烟如萱若南寻真晓亦向珊慕灵以蕊寻雁映易雪柳孤岚笑霜海云凝天沛珊寒云冰旋宛儿绿真盼晓霜碧凡夏菡曼香若烟半梦雅绿冰蓝灵槐平安书翠翠风香巧代云梦曼幼翠友巧听寒梦柏醉易访旋亦玉凌萱访卉怀亦笑蓝春翠靖柏夜蕾冰夏梦松书雪乐枫念薇靖雁寻春恨山从寒忆香觅波静曼凡旋以亦念露芷蕾千帅新波代真新蕾雁玉冷卉紫千琴恨天傲芙盼山怀蝶冰山柏翠萱恨松问旋南白易问筠如霜半芹丹珍冰彤亦寒寒雁怜云寻文乐丹翠柔谷山之瑶冰露尔珍谷雪乐萱涵菡海莲傲蕾青槐洛冬易梦惜雪宛海之柔夏青妙菡春竹痴梦紫蓝晓巧幻柏元风冰枫访蕊南春芷蕊凡蕾凡柔安蕾天荷含玉书雅琴书瑶春雁从安夏槐念芹怀萍代曼幻珊谷丝秋翠白晴海露代荷含玉书蕾听访琴灵雁秋春雪青乐瑶含烟涵双平蝶雅蕊傲之灵薇绿春含蕾梦蓉初丹听听蓉语芙夏彤凌瑶忆翠幻灵怜菡紫南依珊妙竹访烟怜蕾映寒友绿冰萍惜霜凌香芷蕾雁卉迎梦元柏代萱紫真千青凌寒紫安寒安怀蕊秋荷涵雁以山凡梅盼曼翠彤谷新巧冷安千萍冰烟雅友绿南松诗云飞风寄灵书芹幼蓉以蓝笑寒忆寒秋烟芷巧水香映之醉波幻莲夜山芷卉向彤小玉幼";

        if (Random.Range(0,100) >= 50)
        {
            //3字名字
            name = _crabofirstName[UnityEngine.Random.Range(0, _crabofirstName.Length - 1)] + _lastName[UnityEngine.Random.Range(0, _lastName.Length - 1)] + _lastName[UnityEngine.Random.Range(0, _lastName.Length - 1)];
        }
        else
        {
            //2字名字
            name = _crabofirstName[UnityEngine.Random.Range(0, _crabofirstName.Length - 1)] + _lastName[UnityEngine.Random.Range(0, _lastName.Length - 1)];
        }
        return name;
    }
代码示例

 

检测联网

bool _HaveNet = false;

//判断是否连接wifi
if (Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork)
            {
                _HaveNet = true;
            }
//判断是否连接移动网络时         
if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork)
            {
                _HaveNet = true;
            }
代码示例

 

退出游戏

#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#else
            Application.Quit();
#endif
代码示例

 

清除控制台

/// <summary>
/// U3D新版本清空控制台
/// </summary>
public static void ClearConsole()
{
    System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(SceneView));
    Type logEntries = assembly.GetType("UnityEditor.LogEntries");
    System.Reflection.MethodInfo clearConsoleMethod = logEntries.GetMethod("Clear");
    clearConsoleMethod.Invoke(new object(), null);
}

/// <summary>
/// U3D旧版本清空控制台
/// </summary>
public static void ClearConsole_Old()
{
    var logEntries = System.Type.GetType("UnityEditorInternal.LogEntries,UnityEditor.dll");
    var clearMethod = logEntries.GetMethod("Clear", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
    clearMethod.Invoke(null, null);
}
代码示例

 

posted @ 2022-11-04 11:55  桜庭の猫  阅读(213)  评论(0)    收藏  举报