Material和SharedMaterial的區別


簡單概括

Material:使用的時候,如果有其他物體同時在占用這一份,則會復制一份instance出來,只改變對應的這一份。會留存在內存中,不會銷毀。unloadunuse會銷毀。

SharedMaterial:改變參數的時候,所有共用的都會改變。

修改對應的接口,在Editor下使用material,其他情況改為SharedMaterial。renderer.GetShareMaterial.

public Material material { 
get {
if (_sharedMaterial ~= _material){
_material = new Material (_sharedMaterial);
_sharedMaterial = _material;
}

return _material;
}

set {
_sharedMaterial = value;
}
}

public Material sharedMaterial {

get {
return _sharedMaterial;
}

set {
_sharedMaterial = value;
}
}

使用 material 時的內存泄漏問題

每一次引用 Renderer.material 的時候,都會生成一個新的 material 到內存中去,銷毀物體的時候需要我們手動去銷毀該material,否則會一直存在內存中。

官方文檔說:

This function automatically instantiates the materials and makes them unique to this renderer. It is your responsibility to destroy the materials when the game object is being destroyed. Resources.UnloadUnusedAssets also destroys the materials but it is usually only called when loading a new level.

此方法自動實例化該材質並且使其成為該渲染器獨有的材質。當該游戲物體被刪除時,你應該手動刪除該材質。當替換場景調用 Resources.UnloadUnusedAssets 也可以刪除該材質。

網上的解決方案如下:

http://www.xuanyusong.com/archives/2530

編輯器下使用 material, 其他平台使用 sharedMaterial

public static Material GetMaterial(Renderer render) 
{ 
#if UNITY_EDITOR 
    return render.material; 
#else 
    return render.sharedMaterial; 
#endif 
}

 

 

 

 


---------------------
原文:https://blog.csdn.net/david_dai_1108/article/details/71598628
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

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



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