Unity 常用功能整理
安卓摄像头的调用请求与拍摄、截图
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// /// ———————— 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 } }代码示例
随机名字库
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <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; }代码示例
检测联网
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
bool _HaveNet = false; //判断是否连接wifi if (Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork) { _HaveNet = true; } //判断是否连接移动网络时 if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork) { _HaveNet = true; }代码示例
退出游戏
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit(); #endif代码示例
标签:UnityEngine,string,filePath,代码,Permission,工具集,Unity,Android,摄像头 From: https://www.cnblogs.com/sakuraneko/p/16857292.html