Changing materials on RayCastHit

Hi all,

Apologies for the very basic question, I’m extremely new to Unity and scripting and struggling a little with getting this to work the way I want.

Basically I have an object - for learning purposes I’m simply using a Cube, which I want to detect when hit by a raycast. When this Cube detects it has been hit by a raycast, I want it to cycle through an array of materials I have assigned.

I’m somewhat comfortable raycasting towards where I’m clicking:

 if (Input.GetMouseButtonDown(0))

            {
                Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                Debug.DrawRay(mainCam.transform.position, ray.direction, Color.red, 10f);

                if (Physics.Raycast(ray, out hit))
                    hit.collider.gameObject.SendMessage("HitBy");
            }

The code for raycasting is attached to my main camera in the scene.

But I’m not sure how to get these raycasts to be detected by the collider of the Cube, and then for those collisions to cause the current material to cycle forward. I’m also not too sure if I should be writing a new script to attach to the Cube to detect these collisions, or if all of this should be handled in the script from where the raycast originated.

If anyone has any insight that would be extremely helpful. Eventually I’d like to have a system in place where I hover over an item, it displays a white outline indicating that it is interactable, and I can click and select different materials from a menu to be applied to the object. This is obviously a goal slightly further along after I’ve got my head around the basics.

Thanks,

Why not just use OnMouseOver in the cube’s script?

Just checked that out and I can use OnMouseOver instead, but I’m still unsure how to change textures or materials from this.

you can use;

Material mat = GetComponent().material;

to reference the cubes material and then do what you wish with it.

Thanks for the help, I’ve figured it out now.

I had bloated the script with unnecessary things and it got quite confusing. Here is the new script that attaches to the object you want to cycle materials on.

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

public class OnMouseOver : MonoBehaviour {

    public Material[] myMaterials;
    int arrayPos = 0;


    void Start () {
        GetComponent<MeshRenderer>().material = myMaterials[0];
    }
   
    void Update () {
       
    }

    void OnMouseDown()
    {
        arrayPos++;
        arrayPos %= myMaterials.Length;
        GetComponent<MeshRenderer>().material = myMaterials[arrayPos];
    }

}