uintAPi 之Renderer.material

时间:2023-03-09 19:17:06
uintAPi 之Renderer.material

Renderer.material

public Material 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.

解释:该方法会返回第一个(有多个实例材质的情况下),修改材质的化只会修改这个物体的材质颜色,如果该材质有共享体,则会一起改变;
下面给的注意是:这个函数会自动实例化唯一的材质而且,当物体被销毁,则该材质也会被销毁,除非他在新的一层被联系。
我的代码实例:

void OnMouseEnter()
{
if(turretGo==null&&EventSystem.current.IsPointerOverGameObject())
{
renderer.material.color = Color.red;
}
}
void OnMouseExit()
{
renderer.material.color = Color.white;
}

//该代码实现当物体放在一个物体上显示红色,离开显示白色

官方代码实例:

using UnityEngine;
using System.Collections; // Change renderer's material each changeInterval
// seconds from the material array defined in the inspector.
public class ExampleClass : MonoBehaviour
{
public Material[] materials;
public float changeInterval = 0.33F;
public Renderer rend; void Start()
{
rend = GetComponent<Renderer>();
rend.enabled = true;
} void Update()
{
if (materials.Length == 0)
return; // we want this material index now
int index = Mathf.FloorToInt(Time.time / changeInterval); // take a modulo with materials count so that animation repeats
index = index % materials.Length; // assign it to the renderer
rend.sharedMaterial = materials[index];
}
}