Change material of clicked object? (Script in thread)

using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using UnityEngine.SceneManagement;


public class ChangeMaterial : MonoBehaviour
{
    public Renderer[] renderers;
    public Material[] materials;

    private int currentMaterialIndex = 0;

    public void Update()
    {
        if (Input.GetMouseButtonUp(0))
        {
            foreach (Renderer r in renderers)
            {
                r.material = materials[currentMaterialIndex];
            }
            currentMaterialIndex++;
            if (currentMaterialIndex == materials.Length) currentMaterialIndex = 0;
        }
    }
}

Hey guys, I have this working script for my AR project. What it basically does is, it changes the materials of an object when you click somewhere. The problem is: it changes all the materials at once when you click somewhere. When I have lets say two 3d objects showing in my project, I want to change only the materials on the object I clicked on. Is there an easy way to do this?

Yes, but you are not showing us how your are setting up renderers[ ]. Anything in there will be changed when you click the button. So, to change only the mats for the object you click on, only put the renderers of the that object into renderers[ ].

-ch

I’m fairly new to Unity and especially C#, so semantics are making things really hard for me. This is the last part I need to add to my project and I’m done. Mind showing me what code exactly I need to add? Would be really nice.

I wont write the code for you, but I will tell you what to do:

  • after the mouseclick you need the mousePosition
  • from the camera to the direction of the mousePosition you need to shoot a Ray
  • if the Ray intersects with a collider on an object you want to change the material on
  • then you get the renderer and make the change

What you need to research to achieve this:

  • Input mousePosition
  • RaycastHit
  • Physics.Raycast
1 Like

He’s asking you to show how you’re filling your array for renders. If you have nothing in that list, perhaps the program is putting everything into that array and that’s the problem?