- Home /
Unity Editor generate color changes color to all objects and I want to change only to one,Editor extension for specific object
I'm learning Unity and now I want to create a Editor script that will make it possible to generate different color to a cube each time i click on a button "Generate Color".
I've created a CubeLogic
that is attached to one cube gameobject and I also created a CubeLogicEditor
that will handle OnInspectorGUI()
and call method GenerateColor()
from CubeLogic
.
It works just fine unless you have mutliple cubes on a scene then all of the cubes will have the same color that's generated even though only one object has the script attached to it!
CubeLogic.cs GenerateColor()
method:
public void GenerateColor()
{
MeshRenderer meshRenderer = gameObject.GetComponent<MeshRenderer>();
if (meshRenderer)
{
meshRenderer.sharedMaterial.color = Random.ColorHSV();
}
}
CubeLogicEditor.cs OnInspectorGUI()
method:
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
CubeLogic cubeLogic = (CubeLogic) target;
GUILayout.Label("Press the button below to generate a random color!");
if (GUILayout.Button("Generate Color"))
{
if (cubeLogic)
{
cubeLogic.GenerateColor();
}
}
}
So I want to apply this color change only on one cube and not on all cubes. What am I doing wrong?
Answer by CodesCove · Jun 29, 2020 at 07:31 PM
When you change the material color it will be changed for all objects using this same material.
Using PropertyBlock you can control material properties per object: https://docs.unity3d.com/ScriptReference/Renderer.SetPropertyBlock.html
Your answer
Follow this Question
Related Questions
i'm trying to code a premise, if 3 objects are the same color then it will destroy the wall 1 Answer
How to change color of sprite as it moves over different backgrounds 2 Answers
In EditorGUI, how to implement a large Editable Panel like what you can do in an UML diagram? 0 Answers
Changing the label style on a text field in EditorGUILayout 0 Answers