Unity 3D Game Dev Day 3:how to use onCollisionEnter to change the material of the object,how to change using serilizedfiled to have multiple material drag-ed in, and change according to onCollisioEnter?

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

public class OnCollisionChangeMat : MonoBehaviour
{
    [SerializeField]
    private Material[] materials;

    private int currentMatIndex = 0;

    private Renderer renderer;

    void Start()
    {
        renderer = GetComponent<Renderer>();
    }

    void OnCollisionEnter(Collision collision)
    {
        if (materials.Length > 0)
        {
            renderer.material = materials[currentMatIndex];

            currentMatIndex = (currentMatIndex + 1) % materials.Length;
        }
    }
}

image-20240123102424662

Then you can make multiple materials and leter drag into the list.

Get New Tutorials by Email

No spam. Just clear, practical breakdowns you can apply right away.

Enjoy this tutorial?

Get new practical tech tutorials in your inbox.