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;
			}
		}
	}
}

Did my answer fix your problem?

I don't think there is door moving code, instead there is spring joint that is used.

1 Answer

1

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 [ExecuteInEditMode]?

Yup, [ExecuteInEditMode] worked! Just tried it.

Exactly. The door is a rigidbody with a hinge joint. What I need is if the player is away by X of distance, then the object will fall = null. However, it's harder then it sounds I think.