Renderer.material 与Renderer.sharedMaterial 的区别
material
Returns the first instantiated Material assigned to the renderer.
Modifying material will change the material for this object only.
If the material is used by any other renderers, this will clone the shared material and start using it from now on.
Note: 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 也会破坏材质,但通常仅在加载新关卡时调用。
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
Material m_Material;
void Start()
{
m_Material = GetComponent<Renderer>().material;
print("Materials " + Resources.FindObjectsOfTypeAll(typeof(Material)).Length);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
print("Materials " + Resources.FindObjectsOfTypeAll(typeof(Material)).Length);
Destroy(gameObject);
}
}
void OnMouseOver()
{
m_Material.color = Color.red;
}
void OnMouseExit()
{
m_Material.color = Color.white;
}
void OnDestroy()
{
Destroy(m_Material);
print("Materials " + Resources.FindObjectsOfTypeAll(typeof(Material)).Length);
}
}
sharedMaterial
Modifying sharedMaterial will change the appearance of all objects using this material, and change material settings that are stored in the project too.
It is not recommended to modify materials returned by sharedMaterial. If you want to modify the material of a renderer use material instead.
修改 sharedMaterial 将改变所有使用此材质的对象的外观,并更改存储在项目中的材质设置。 不建议修改 sharedMaterial 返回的材质。
如果要修改渲染器的材质,请改用material 。
总结
Renderer.sharedMaterial :当多个Renderer共用一个材质时,修改Renderer.sharedMaterial 将修改所有引用它的Renderer。 Renderer.material :修改Renderer.material 只会影响Renderer本身。
运行实例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Change_T : MonoBehaviour
{
public GameObject Cube;
public Texture Card_01;
void Start()
{
}
void Update()
{
}
public void Button_T()
{
Cube.GetComponent<Renderer>().sharedMaterial.mainTexture = Card_01;
}
}
由图可见,此时Cube模型的材质是Mat_Red,是没有贴图的;我们运行一次并按下Button按钮可见,Mat_Red的贴图已经换成了Card_01
|