What is wrong with my script to change shader on all GameObjects?
I wrote this script so that I wouldn't have to change each material manually, but so that the script would do the work for me.
However it's not working. And yes, I have the shader assigned in the inspector.
using UnityEngine;
using System.Collections;
public class ToonMaterialScript : MonoBehaviour {
// Array to store all the GameObjects in the scene
GameObject[] AllGameObjects;
// Shader assigned in the inspector
public Shader Shader;
// Use this for initialization
void Start () {
// Find All GameObjects
AllGameObjects = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
// Loop through all GameObjects
foreach (GameObject go in AllGameObjects) {
// If the Gameobject has a material
if (go.GetComponent<Material>()) {
// Get the material of the gameobject
Material mat = go.GetComponent<Material> ();
// Set the shader of the material of the gameobject
mat.shader = Shader;
}
}
}
}
Answer by CodeElemental · Jul 22, 2016 at 10:46 AM
You cannot directly change the Material used to render an object. Instead you can access it via the Renderer component.
Something like this :
foreach (GameObject go in AllGameObjects) {
// If the Gameobject has a material
if (go.GetComponent<Renderer>()) {
// Get the material of the gameobject
Material mat = go.GetComponent<Renderer> ().material;
// Set the shader of the material of the gameobject
mat.shader = Shader;
}
}
Awesome it worked.
However I thought that if I would run the script once, the materials shaders would stay that shader even when I stop the gameview.
(That is usually when you manually edit the shaders during run time)
How can I make them stay that shader even when exiting unity preview?
Should I use [ExecuteInEdit$$anonymous$$ode]?
Yup, [ExecuteInEdit$$anonymous$$ode] worked! Just tried it.
Your answer
Follow this Question
Related Questions
How to add wait for second for a Editor Script? 0 Answers
Character Movement jerking 0 Answers
The laser problems 0 Answers
Vector3.Lerp in update, how stop? 1 Answer
Touch Force on 3D Object 2 Answers