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 a
reversePathstring with the number of levels of the root directory of the
ContentManager. The problem is accessing the full directory of the
ContentManager` 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):
Add a reference to System.Windows.Forms to your project
Add the following code to the top of your Game1.cs file:
using System.IO; using TApplication = System.Windows.Forms.Application;
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*");