项目中unity遇到的错误解决(为自己)2021

这篇博客汇总了Unity中遇到的文件I/O错误,如IOException:Sharing violation on path,以及如何解决,如确保文件流正确关闭。还提到了纹理压缩对图标质量的影响,以及如何设置压缩选项。此外,文章讨论了通过PackageManager获取包信息的方法,并解决了路径过长导致的异常。
摘要由CSDN通过智能技术生成

///

空apk Scripting Backend Mono 17963KB Scripting Backend IL2CPP 12644KB Scripting Backend IL2CPP和Strip Engine Code 开启和Managed Stripping Level High 7912KB
空weggl 25279.27KB

Q: Unity IOException: Sharing violation on path

A: 项目中有两个FileStream  忘了关闭文件流,我不知道你的跟我一不一样的情况
 解决办法:Ctrl + F,搜索项目里所有的  FileStream , 看结尾有没有关闭文件流
 fs.Flush();
 fs.Close();
 示例:

// 截图
        IEnumerator ScreenShoot()
        {
            yield return new WaitForEndOfFrame();//等某一帧结束
            Texture2D t = new Texture2D(cameraTexture.width, cameraTexture.height);
            t.SetPixels(cameraTexture.GetPixels());
            t.Apply();
            byte[] byt = t.EncodeToPNG();
            // 该函数会直接覆盖已存在的同名文件
           // File.WriteAllBytes(screenCapturePath, byt);
            FileStream fs = File.Open(screenCapturePath, FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite);
            fs.Write(byt, 0, byt.Length);
            fs.Flush();
            fs.Close();

            Debug.Log("图片已保存");
#if UNITY_EDITOR || UNITY_ANDROID
            //这里的代码在IOS和Android平台都会编译
            UnityEditor.AssetDatabase.Refresh();
#endif

        }

A:在写入文件的过程中一直报这个错误,大致意思是共享破坏的意思,可能是路径操作中出现了问题。fi = new FileInfo(LogPath);
  if (!fi.Exists)
    sw = fi.CreateText();
  else
    sw = fi.AppendText();
  sw = fi.AppendText();
  sw.WriteLine(log);
  sw.Close();

查询了一下说读写完文件需要调用Close函数。如上是已经调用了,其实是不小心多写了行。

解决

删除第二行 sw = fi.AppendText()即可。
从这里看出,写一次必须调用Close函数。

A:    It looks like you still have a lock on the file you're trying to write to. And I think it might have something to do with the File.Create() method you're calling right before trying to access it with the StreamWriter.

I'm not familiar with JavaScript but in C# it's possible to dispose the File.Create method right away like:

File.Create("filepath").Dispose();

Also, In C# it's not necessary to create the file before using the StreamWriter so you can leave the File.Create() part out completely. I'm not sure if it will work in JS though.

/

Compressed texture myGame_logo is used as icon. This might compromise visual quality of the final image. Uncompressed format might be considered as better import option.
UnityEngine.StackTraceUtility:ExtractStackTrace ()
UnityEditor.BuildPipeline:BuildPlayerInternal (string[],string,string,UnityEditor.BuildTargetGroup,UnityEditor.BuildTarget,UnityEditor.BuildOptions)
UnityEditor.BuildPipeline:BuildPlayer (string[],string,string,UnityEditor.BuildTargetGroup,UnityEditor.BuildTarget,UnityEditor.BuildOptions)
UnityEditor.BuildPipeline:BuildPlayer (UnityEditor.BuildPlayerOptions)

解决方法:

fixed it by turning compression off for all devices

As best I know, it's a harmless warning about the "start" icon. My iPad apps run perfectly and the icon looks fine to me, but I get that error everytime.

I assume it's saying "Look, my start icon is always exactly 209 by 197. You and I know, that I could fit a 1024x1024 lossy-compressed jpeg in there. But 209x197 is not that many pixels, so why not give me that exact size, exactly how they will appear?"

It fixed by setting up the compression format to "truecolor".
Also make sure the icon is in proper size. Example: Android default playstore icon is 512x512

How get PackageInfo by name and version?

  1. public static IEnumerable<Sample> FindByPackage(string packageName, string packageVersion)

  2.         {

  3.             var package = PackageDatabase.instance.GetPackage(packageName);

  4.             if (package != null)

  5.             {

  6.                 var version = package.versions.installed;

  7.                 if (!string.IsNullOrEmpty(packageVersion))

  8.                     version = package.versions.FirstOrDefault(v => v.version == packageVersion);

  9.                 if (version != null)

  10.                     return version.samples;

  11.             }

  12.             return new List<Sample>();

  13.         }

  1. List<PackageInfo> packageJsons = AssetDatabase.FindAssets("package")

  2.                 .Select(AssetDatabase.GUIDToAssetPath).Where(x => AssetDatabase.LoadAssetAtPath<TextAsset>(x) != null)

  3.                 .Select(PackageInfo.FindForAssetPath).ToList();

  4. return packageJsons.Any(x => x.name == _hdrpPackageName && x.version == _hdrpPackageVersion);

First you search for the package you need info of (TMP) with PackageManager.Client (I think it will look something like this: var tmp = Client.Search("com.unity.textmeshpro").Result;, be aware that .Result is synchronous, maybe there's a better way to implement this using Tasks).

Then you get the package's info (version) with PackageManager.PackageInfo (something like tmp.version). Done.

Actually I jumped the gun. The result is null. PackageInfo[] textmeshpro = Client.Search("com.unity.textmeshpro").Result;

public class PackageVersion : ScriptableObject
{
    // See https://docs.unity3d.com/ScriptReference/HideInInspector.html
    [HideInInspector] public string Version;

#if UNITY_EDITOR
    // Called automatically after open Unity and each recompilation
    // See https://docs.unity3d.com/ScriptReference/InitializeOnLoadMethodAttribute.html
    [InitializeOnLoadMethod]
    private static void Init()
    {
        // See https://docs.unity3d.com/ScriptReference/Compilation.CompilationPipeline-compilationFinished.html
        // Removing the callback before adding it makes sure it is only added once at a time
        CompilationPipeline.compilationFinished -= OnCompilationFinished;
        CompilationPipeline.compilationFinished += OnCompilationFinished;
    }

    private static void OnCompilationFinished()
    {
        // First get the path of the Package
        // This is quite easy since this script itself belongs to your package's assemblies
        var assembly = typeof(PackageVersion).Assembly;

        // See https://docs.unity3d.com/ScriptReference/PackageManager.PackageInfo.FindForAssembly.html
        var packageInfo = PackageManager.PackageInfo.FindForAssembly();

        // Finally we have access to the version!
        var version = packageInfo.version;

        // Now to the ScriptableObject instance
        // Try to find the first instance
        // See https://docs.unity3d.com/ScriptReference/AssetDatabase.FindAssets.html
        // See https://docs.unity3d.com/ScriptReference/PackageManager.PackageInfo-assetPath.html
        var guid = AssetDataBase.FindAssets($"t:{nameof(PackageVersion)}", packageInfo.assetPath). FirstOrDefault();
        PackageVersion asset;
        if(!string.isNullOrWhiteSpace(guid))
        {
            // See https://docs.unity3d.com/ScriptReference/AssetDatabase.GUIDToAssetPath.html
            var path = AssetDatabase.GUIDToAssetPath(guid);
            // See https://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html
            asset = AssetDatabase.LoadAssetAtPath<PackageVersion>(path);                          
        }
        else
        {

            // None found -> create a new one
            asset = ScriptableObject.CreateInstance<PackageVersion>();
            asset.name = nameof(PackageVersion);
            // make it non editable via the Inspector
            // See https://docs.unity3d.com/ScriptReference/HideFlags.NotEditable.html
            asset.hideFlags = HideFlags.NotEditable;

            // Store the asset as actually asset
            // See https://docs.unity3d.com/ScriptReference/AssetDatabase.CreateAsset.html
            AssetDataBase.CreateAsset(asset, $"{packageInfo.assetPath}/{nameof(PackageVersion)}");
        }

        asset.Version = version;

        // See https://docs.unity3d.com/ScriptReference/EditorUtility.SetDirty.html
        EditorUtility.SetDirty(asset);
    }
#endif
}

/

未经处理的异常:  System.Exception: On Windows the Unity checkout should be at short enough path (recommend under 48 chars). Yours is 68, which is way too much.

[UnityEditor.Callbacks.OnOpenAsset] public static void OnOpenAsset(int instanceID, int line){} Call Stack:

Boolean UnityEditor.AssetDatabase:OpenAsset (Int32, Int32)+0x4 at :-1
Boolean UnityEditor.AssetDatabase:OpenAsset (Int32)+0x3 at :-1
Void UnityEditor.ProjectBrowser:OpenAssetSelection (Int32[])+0x18 at :-1
Void UnityEditor.ProjectBrowser:OpenListAreaSelection ()+0x6b at :-1
Void UnityEditor.ProjectBrowser:ListAreaItemSelectedCallback (Boolean)+0x93 at :-1
Void UnityEditor.ObjectListArea:SetSelection (Int32[], Boolean)+0x25 at :-1
Void LocalGroup:HandleMouseWithDragging (AssetReference, Int32, Rect)+0x95 at :-1
Void LocalGroup:DrawItem (Rect, FilterResult, BuiltinResource, Boolean)+0xdf6 at :-1
Void LocalGroup:DrawInternal (Int32, Int32, Single)+0x155 at :-1
Void Group:Draw (Single, Vector2, Int32)+0x155 at :-1
Void UnityEditor.ObjectListArea:HandleListArea ()+0x16f at :-1
Void UnityEditor.ObjectListArea:OnGUI (Rect, Int32)+0x173 at :-1
Void UnityEditor.ProjectBrowser:OnGUI ()+0x203 at :-1
Void UnityEditor.HostView:InvokeOnGUI (Rect, Rect)+0x66 at :-1
Void UnityEditor.DockArea:DrawView (Rect, Rect)+0x4 at :-1
Void UnityEditor.DockArea:OldOnGUI ()+0x19d at :-1
Void UnityEngine.UIElements.IMGUIContainer:DoOnGUI (Event, Matrix4x4, Rect, Boolean, Rect, Action, Boolean)+0x1e1 at :-1
Boolean UnityEngine.UIElements.IMGUIContainer:HandleIMGUIEvent (Event, Matrix4x4, Rect, Action, Boolean)+0xc8 at :-1
Boolean UnityEngine.UIElements.IMGUIContainer:HandleIMGUIEvent (Event, Action, Boolean)+0x25 at :-1
Boolean UnityEngine.UIElements.IMGUIContainer:HandleIMGUIEvent (Event, Boolean)+0xa at :-1
Boolean UnityEngine.UIElements.IMGUIContainer:SendEventToIMGUIRaw (EventBase, Boolean, Boolean)+0x2a at :-1
Boolean UnityEngine.UIElements.IMGUIContainer:SendEventToIMGUI (EventBase, Boolean, Boolean)+0x154 at :-1
Void UnityEngine.UIElements.IMGUIContainer:HandleEvent (EventBase)+0x5d at :-1
Void UnityEngine.UIElements.EventDispatchUtilities:PropagateEvent (EventBase)+0x12f at :-1
Boolean UnityEngine.UIElements.MouseEventDispatchingStrategy:SendEventToRegularTarget (EventBase, BaseVisualElementPanel)+0x13 at :-1
Boolean UnityEngine.UIElements.MouseEventDispatchingStrategy:SendEventToTarget (EventBase, BaseVisualElementPanel)+0x3 at :-1
Void UnityEngine.UIElements.MouseEventDispatchingStrategy:DispatchEvent (EventBase, IPanel)+0x2a at :-1
Void UnityEngine.UIElements.EventDispatcher:ApplyDispatchingStrategies (EventBase, IPanel, Boolean)+0x28 at :-1
Void UnityEngine.UIElements.EventDispatcher:ProcessEvent (EventBase, IPanel)+0x47 at :-1
Void UnityEngine.UIElements.EventDispatcher:ProcessEventQueue ()+0x39 at :-1
Void UnityEngine.UIElements.EventDispatcher:OpenGate ()+0x3c at :-1
Void UnityEngine.UIElements.EventDispatcherGate:Dispose ()+0x7 at :-1
Void UnityEngine.UIElements.EventDispatcher:ProcessEvent (EventBase, IPanel)+0x11a at :-1
Void UnityEngine.UIElements.EventDispatcher:Dispatch (EventBase, IPanel, DispatchMode)+0x49 at :-1
Void UnityEngine.UIElements.BaseVisualElementPanel:SendEvent (EventBase, DispatchMode)+0x1f at :-1
Boolean UnityEngine.UIElements.UIElementsUtility:DoDispatch (BaseVisualElementPanel)+0xe3 at :-1
Boolean UnityEngine.UIElements.UIElementsUtility:UnityEngine.UIElements.IUIElementsUtility.ProcessEvent (Int32, IntPtr, Boolean)+0x3f at :-1
Boolean UnityEngine.UIElements.UIEventRegistration:ProcessEvent (Int32, IntPtr)+0x1f at :-1
Boolean <>c:<.cctor>b__1_2 (Int32, IntPtr)+0x3 at :-1
Void UnityEngine.GUIUtility:ProcessEvent (Int32, IntPtr, Boolean)+0x18 at :-1

///

/

//

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值