【问题标题】:Loading Texture2D Inconsistently Fails加载 Texture2D 不一致地失败
【发布时间】:2015-04-22 20:00:14
【问题描述】:

有时(并非总是如此,大多数时候它可以完美运行),当它无法加载 Texture2D 时,我会捕捉到我提供的异常。

public static class Extras
{
    public static class Load
    {
        private static Dictionary<string, Texture2D> Textures;

        public static Texture2D Texture(string Path)
        {
            if (Textures == null) Textures = new Dictionary<string, Texture2D>();
            if (Textures.ContainsKey(Path)) return Textures[Path];
            else
            {
                try { Textures.Add(Path, Service<ContentManager>().Load<Texture2D>(Path)); return Textures[Path];
                catch { throw new ArgumentNullException(string.Format("Failed to load Texture2D from \"{0}\"!", Path)); }
            }
            return null;
        }
    }

    public static class Services
    {
        private static GameServiceContainer Container;

        public static T Get<T>() { return (T)Container.GetService(typeof(T)); }
        public static void Add<T>(T Service) { if (Container == null) Container = new GameServiceContainer(); Container.AddService(typeof(T), Service); }
        public static void Remove<T>() { Container.RemoveService(typeof(T)); }
    }
    public static T Service<T>() { return Services.Get<T>(); }
}

-

游戏加载时:

Extras.Services.Add<ContentManager>(Content);

Texture2D Texture = Extras.Load.Texture("Textures\\Player");

现在大多数情况下它都能正常工作,但有时我会遇到异常(第一次将纹理加载到游戏中时)。

为什么加载 Texture2D 总是失败?

【问题讨论】:

  • 究竟是什么异常?
  • @Silveor "catch { throw new ArgumentNullException(string.Format("Failed to load Texture2D from \"{0}\"!", Path)); }"

标签: c# xna loading texture2d


【解决方案1】:

首先,format your code,特别是如果你要发布它。

try
{
    Textures.Add(Path, Service<ContentManager>().Load<Texture2D>(Path));
    return Textures[Path];
}
catch
{
    throw new ArgumentNullException(string.Format("Failed to load Texture2D from \"{0}\"!", Path));
}

或者在复制代码 sn-p 之前直接按 Ctrl+E、Ctrl+D(在我的 VS 2010 中默认)。

其次,部分 catch 应该处理已经抛出的异常,但你忽略它只是抛出一个新的异常。另请注意,ArgumentNullException 是 Exception 的一个特殊子类,当尝试访问不存在的对象时会发生这种情况。如果你想抛出自定义异常,它应该在逻辑上对应于这种情况。如果您不能 100% 确定发生了什么,请抛出基本的 Exception 对象。

try
{
    // critical code section
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.Message);
}

请阅读有关 try-catch 的文档以了解其工作原理。

最后。在 Visual Studio(我的是 2010)中,您可以转到 Debug -> Exceptions 项目并选中第一个“CLR Exceptions”复选框。它允许您在抛出运行时异常后立即查看它们。

【讨论】:

  • 我在 2010 年,我找不到那个选项,虽然我认为它已经启用,但当它们在调试模式下抛出时,我会看到我的异常。
  • 那么,到底是什么异常呢?如果你看到它,你应该很容易确定它的来源。
  • 显然 ContentManager 为空。
猜你喜欢
  • 2016-09-05
  • 2012-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
相关资源
最近更新 更多