Automatic instantiation of
If you want to modify any game resource, you typically want to modify it at run time, and the modification is temporary. For example, if the character is invincible, you may want to change the shader (shader)of the material (material) so that the player character can visually display the invincible state. This action includes modifying the material being used. This modification is not permanent because we do not want the shader to be different from the material when we exit Play mode .
However, it is possible to write scripts in Unity to permanently modify the source resources. Let's start with the material example above.
To temporarily change the shader for a material, you can change the shader (shader) property in the material (material) component.
private var Invincibleshader = Shader.find ("specular"); function startinvincibility {renderer.material.shader = Invincibleshader;}
When you use this script and exit Play mode, the state of the material (material) is reset to the pre-play mode. This occurs because the material is automatically instantiated and returned to the instance whenever renderer.material is accessed. The instance is automatically and simultaneously applied to the renderer. So you can make changes according to your own wishes without worrying about performance issues.
Direct modification of important information
The following methods will modify the true source resource files used in Unity. These modifications cannot be undone. Please use it carefully.
Now, let's say we don't want to reset the material when we exit playback mode. To do this, you can use renderer.sharedmaterial. The Sharedmaterial property returns the true resources used by the renderer (and other renderers).
The following code permanently changes the material used by the highlight (specular) shader. The status of the material is not reset to the state before play mode.
private var Invincibleshader = Shader.find ("specular"); function startinvincibility {renderer.sharedMaterial.shader = Invincibleshader;}
As you can see, making any changes to sharedmaterial is both dangerous and risky. These changes will be permanent and cannot be undone.
Applicable class Members
The same formula above can be applied to items other than the material. A complete list of resources that meet this requirement is as follows:
- Material (materials): Renderer.material and Renderer.sharedmaterial
- Grid (Meshes): Meshfilter.mesh and Meshfilter.sharedmesh
- Physical material (physic materials): Collider.material and Collider.sharedmaterial
Directly specify
If you declare a public variable that is in the same category: material (materials), mesh (Meshes), or physical material (physic materials), and use that variable instead of the associated class member to modify the resource, you will not get the advantage of automatic instantiation before applying the modification.
Unity modifies source resources through scripting