- Home /
Question by
aljndrrr · Apr 12, 2012 at 05:51 PM ·
gameobjectmaterials
Changing a material using Unity Editor Script
I have the following game object
MyGameObject
-MeshRenderer
----Materials:
----- Size: 1
----- Element 0: MyGameObjectMaterial
I want to change the gameobject material using a Unity Editor Script, my script looks similar to this
using UnityEngine;
using UnityEditor;
using System.Collections;
public class BuildingAutomator : EditorWindow
{
public GameObject myGameObject;
public Material myNewMaterial;
// Add menu named "My Window" to the Window menu
[MenuItem("Window/My Window")]
static void Init()
{
// Get existing open window or if none, make a new one:
BuildingAutomator window = (BuildingAutomator)EditorWindow.GetWindow(typeof(BuildingAutomator));
}
void OnGUI()
{
if(GUILayout.Button("Change material!"))
{
myGameObject.renderer.materials[0] = myNewMaterial; //<--- Error
}
}
}
But it throws the following error:
Instantiating material due to calling renderer.material during edit mode. This will leak materials into the scene. You most likely want to use renderer.sharedMaterial instead.
UnityEngine.Renderer:get_materials()
Any suggestions?
Comment
Answer by DaveA · Apr 12, 2012 at 06:40 PM
You most likely want to use renderer.sharedMaterial instead.
myGameObject.renderer.sharedMaterials[0] = myNewMaterial;
It doesn't throws any errors (neither do myGameObject.renderer.materials[0]) but it doesn't assign the material...
I create the material on the "Project", then assign it a shader. Because myNew$$anonymous$$aterial is public I just drag and drop it from the "Project".