Modifying Source Assets Through Scripting
Unity Manual > Advanced > Modifying Source Assets Through Scripting

Modifying Source Assets Through Scripting

Automatic Instantiation

Часто возникает необходимость временно изменять ресурсы во время игры. Например, персонаж подбирает бонус увеличения силы. Необходимо сменить шейдер материала для этого персонажа, чтобы визуально отобразить его состояние. Но это изменение материала не должно быть постоянным и должно быть отменено после выхода из Play Mode.

Однако, Unity позволяет писать скрипты, которые перманентно измению исходные ресурсы. В качестве отправной точки используем приведённый выше пример с маттериалом.

To temporarily change the material's shader, we change the shader property of the material component.

Чтобы временно изменить шейдер материала, мы изменяем свойство shader компонента material.

	private var invincibleShader = Shader.Find ("Specular");

	function StartInvincibility {
		renderer.material.shader = invincibleShader;
	}

Когда используется этот скрипт и происходит выход из Play Mode, состояние материала будет возвращено к исходному. This happens because whenever renderer.material is accessed, the material is automatically instantiated and the instance is returned. This instance is simultaneously and automatically applied to the renderer. So you can make any changes that your heart desires without fear of permanence.

Direct Modification

IMPORTANT NOTE

The method presented below will modify actual source asset files used within Unity. These modifications are not undoable. Use them with caution.

Now let's say that we don't want the material to reset when we exit play mode. For this, you can use renderer.sharedMaterial. The sharedMaterial property will return the actual asset used by this renderer (and maybe others).

The code below will permanently change the material to use the Specular shader. It will not reset the material to the state it was in before Play Mode.

	private var invincibleShader = Shader.Find ("Specular");

	function StartInvincibility {
		renderer.sharedMaterial.shader = invincibleShader;
	}

As you can see, making any changes to a sharedMaterial can be both useful and risky. Any change made to a sharedMaterial will be permanent, and not undoable.

Applicable Class Members

The same formula described above can be applied to more than just materials. The full list of assets that follow this convention is as follows:

Direct Assignment

If you declare a public variable of any above class: Material, Mesh, or Physic Material, and make modifications to the asset using that variable instead of using the relevant class member, you will not receive the benefits of automatic instantiation before the modifications are applied.

Assets that are not automatically instantiated

There are two different assets that are never automatically instantiated when modifying them.

Any modifications made to these assets through scripting are always permanent, and never undoable. So if you're changing your terrain's heightmap through scripting, you'll need to account for instantiating and assigning values on your own. Same goes for Textures. If you change the pixels of a texture file, the change is permanent.