MeshFilter mesh vs sharedMesh


MeshFilter有兩個屬性mesh和sharedMesh,從官方文檔和實際使用來說說這兩者的區別

MeshFilter文檔

Unity的MeshFilter文檔:https://docs.unity3d.com/ScriptReference/MeshFilter.html

mesh Returns the instantiated Mesh assigned to the mesh filter.
sharedMesh Returns the shared mesh of the mesh filter.

mesh訪問的是一個新的object(新實例)

sharedMesh是原始資源,所有實例的屬性共用同一份,也就是說修改它共用屬性全部實例都會發生改變,如果在編輯器下且直接對原始資源的sharedMesh進行修改,則原始資源也會發生改變。

使用情景

如果我們不需要修改mesh中具體的屬性,僅僅是對它賦值的話(比如從ab中加載出來進行設置或替換),那么使用sharedMesh

如果在Editor腳本開發中,需要修改mesh中的數據,則使用mesh

mesh文檔解釋

關於mesh的unity文檔解釋:

Returns the instantiated Mesh assigned to the mesh filter.

If no mesh is assigned to the mesh filter a new mesh will be created and assigned.

If a mesh is assigned to the mesh filter already, then first query of mesh property will create a duplicate of it, and this copy will be returned. Further queries of mesh property will return this duplicated mesh instance. Once mesh property is queried, link to the original shared mesh is lost and MeshFilter.sharedMesh property becomes an alias to mesh. If you want to avoid this automatic mesh duplication, use MeshFilter.sharedMesh instead.

By using mesh property you can modify the mesh for a single object only. The other objects that used the same mesh will not be modified.

It is your responsibility to destroy the automatically instantiated mesh when the game object is being destroyed. Resources.UnloadUnusedAssets also destroys the mesh but it is usually only called when loading a new level.

翻譯成中文如下:

如果一個mesh已經被分配給MeshFilter,那么第一次查詢mesh屬性會創建一個副本,這個副本會被返回。進一步查詢mesh屬性將返回這個復制的mesh實例。一旦mesh屬性被查詢,鏈接到原始共享網格會丟失,MeshFilter.sharedMesh屬性成為mesh的別名。如果你想避免這種自動生成副本,使用MeshFilter.sharedMesh代替。

通過使用mesh屬性,您可以僅修改單個對象的mesh。其他使用相同mesh的對象將不會被修改。

當游戲對象被銷毀時,銷毀自動實例化的mesh是你的責任。UnloadUnusedAssets也會破壞mesh,但通常只在Scene.LoadNewLevel時調用。

mesh偽代碼

猜測mesh的實現代碼大致如下:

public class MeshFilter ...
{
	...
	private Mesh _mesh;
	public Mesh mesh
	{
		get
		{
			if (_mesh == null) 
			{
				_mesh = new Mesh();
				Copy(sharedMehs, _mesh);
			}
			return _mesh;
		}
	}
	...
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM