How Do I Load A XNA Model From A File Path Instead Of From The Content (eg. Model.FromStream but it doesnt exist)

别说谁变了你拦得住时间么 提交于 2019-12-12 20:00:32

问题


How do I load an XNA model from a file path instead of from the content (eg. Model.FromStream but it doesnt exist)?? Texture2D has .FromStream, how can I do the equivalent for Model?


回答1:


You can use Content.Load<Model>("Path here, make sure you use drive letter");

If you really need to have a FromStream method on Model you can use extension methods (Not exactly a perfect duplicate of FromStream but it should work):

public static Model FromPath(this Model model, ContentManager content, string path)
{
    return content.Load<Model>(path);
}

EDIT:

I have just tested the above code and apparently, rather than using the drive letter, you need to match the number of "..\\" in areversePathstring with the number of levels of the root directory of theContentManager. The problem is accessing the full directory of theContentManager` which is private (or protected, I'm not sure). Short of using reflection I don't think that that variable can be accessed. If we do know the full Root Directory Path then this should work:

string reversePath = "";
foreach (string level in Content.FullRootDirectory.Split('\\'))// I know there isn't actually a property 'FullRootDirectory' but for the sake of argument,
{
    reversePath += "..\\";
}
reversePath = reversePath.Substring(4);

I've googled a few times and haven't been able to find a way to get the root directory of the ContentManager. I might even ask this as a question here on SO in a bit here.

OK here is the final thing (using the answer from the question linked to above):

  1. Add a reference to System.Windows.Forms to your project

  2. Add the following code to the top of your Game1.cs file:

    using System.IO;
    using TApplication = System.Windows.Forms.Application;
    
  3. Add this code wherever you need it, like in LoadContent or an extension method:

    string ContentFullPath = Path.Combine(Path.GetDirectoryName(TApplication.ExecutablePath),
    Content.RootDirectory);
    
    string reversePath = "";
    foreach (string level in ContentFullPath.Split('\\'))
    {
        reversePath += "..\\";
    }
    
    reversePath = reversePath.Substring(3);
    
    
    Model test = Content.Load<Model>(Path.Combine(ContentFullPath, reversePath) + "*Your file name here*");
    


来源:https://stackoverflow.com/questions/8694707/how-do-i-load-a-xna-model-from-a-file-path-instead-of-from-the-content-eg-mode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!