如何在Xamarin.iOS中将IMTLTexture赋值给SCNMaterialProperty的Contents?
I get exactly where you're stuck here—Swift handles the bridging between Metal textures and SceneKit's material properties seamlessly, but Xamarin's C# type system requires a bit more explicit handling for this conversion. Here are two reliable ways to fix that invalid cast error:
1. Cast the IMTLTexture to its concrete implementation
The CreateTexture method returns an IMTLTexture interface, but the underlying object is actually a MTLTexture (which inherits directly from NSObject). You can safely cast it to the concrete type first:
// Your existing texture creation IMTLTexture texture = device.CreateTexture(textureDescriptor); // Cast to the concrete MTLTexture class MTLTexture metalTexture = (MTLTexture)texture; // Assign to the material property if (node.Geometry?.FirstMaterial == null) { // Make sure the material exists before accessing it node.Geometry.FirstMaterial = new SCNMaterial(); } node.Geometry.FirstMaterial.Diffuse.Contents = metalTexture;
2. Use double casting to NSObject
If you prefer to work with the IMTLTexture interface directly, you can first cast it to object (to unbox the underlying Objective-C instance) and then to NSObject:
// Your existing code IMTLTexture texture = device.CreateTexture(textureDescriptor); SCNNode node = new SCNNode(); // Assign geometry, etc. // Safe conversion via object intermediate if (node.Geometry?.FirstMaterial != null) { node.Geometry.FirstMaterial.Diffuse.Contents = (NSObject)(object)texture; }
Why this works
In Swift, the compiler automatically bridges Objective-C types like MTLTexture to the appropriate Swift types and handles the assignment to SCNMaterialProperty.Contents without extra work. In Xamarin, since IMTLTexture is a C# interface wrapping the Objective-C class, you need to explicitly access the underlying NSObject-compatible instance either by casting to the concrete MTLTexture class or using the double cast trick.
内容的提问来源于stack exchange,提问作者michasaurus

