Change texture on collision with a raycast - Unity - C#


To change the texture of an object when it collides with a raycast from another object in Unity, you can use a script to detect the collision and then change the texture of the object. Here is an example of how you might do this:

  1. Attach a script to the object that will be emitting the raycast.
  2. In the script, use the Raycast function to detect when the raycast hits another object. You can use the RaycastHit object to get information about the collision, such as the collider and the point of impact.
  3. When a collision is detected, get the object that was hit by the raycast. You can do this by using the collider.gameObject property of the RaycastHit object.
  4. Get the renderer component of the object that was hit, and use it to access the material of the object.
  5. Use the SetTexture function of the material to change the texture of the object.

Here is some sample code that demonstrates how to do this:


public class RaycastTextureChanger : MonoBehaviour
{
    public Texture newTexture;

    void Update()
    {
        Ray ray = new Ray(transform.position, transform.forward);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit))
        {
            GameObject hitObject = hit.collider.gameObject;
            Renderer renderer = hitObject.GetComponent<Renderer>();

            if (renderer != null)
            {
                Material material = renderer.material;
                material.SetTexture("_MainTex", newTexture);
            }
        }
    }
}



This code will change the texture of the object that is hit by the raycast to the texture specified in the newTexture public variable. You can use this same technique to change other properties of the material, such as the color or the shininess.