- Home /
The question is answered, right answer was accepted
How do I change the color of a specific object in a group that share the same script?
I've created a script that changes the material color of an object when you click on it. But I need the script to be shared among multiple objects, but only change the color of the object I click on. Currently, it changes the color of all the objects the script is attached to. The objects will all be the same prefab, just spaced across the screen.
public void Start () {
rend = GetComponent<Renderer>();
rend.enabled = true;
}
// Update is called once per frame
void Update()
{
if ( Input.GetMouseButtonDown(0) )
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if ( Physics.Raycast(ray , out hit , 100) )
{
rend.material.color = Color.green;
}
}
}
Is creating one script and attaching it to a prefab the wrong approach, or am I missing something else?
Answer by hexagonius · Aug 20, 2017 at 09:08 AM
You're only checking if you hit something, not what you hit. With an additional check if what you hit was itself, it should work.
But as an additional hint: raycast for each object is a little to much if only one result matters. I'd put the raycast logic onto another gameobject, unrelated. In there, with the hit.gameobject you should be able to get a script or the renderer or anything and perform the action there.in words.
If I hit something, get the renderer from what I hit and if it has one change it's color
Follow this Question
Related Questions
How can I make objects change color, then fade/return to its original color? 1 Answer
Changing font color in timer script (js) 0 Answers
How do I get my object to change colors randomly? 0 Answers
change color of a cube having touched by Line Renderer 0 Answers
Having trouble resetting the color of an object after the trigger leaves 0 Answers