Search code examples
unity-game-enginecollider

How to change a material in Unity using a script on collison


I am currently making a mobile game in Unity3D. I want it so that when a ball with the tag 'Damage' is collided with, it will change the material of a damage indicator at the top of the screen. Is there an easy way to do this?

Thank you in advance.


Solution

  • You would typically put something like "damage indicator" in your "GameManager" and a GameManager is usually a singleton. It means you on time of collision, you can check the collider tag, if it's "Damage" then you call a function in your GameManager to change the material of your "damage indicator". Something like this:

    public class ExampleClass : MonoBehaviour
    {
    
        ....
    
        void OnCollisionEnter(Collision collision)
        {
            if (collision.gameObject.tag == "Damage")
                GameManager.instance.DamageDone();
        }
    }
    

    GameManager:

    public class GameManager : MonoBehaviour
    {
        public static GameManager instance;
    
        public Material damageMat;
        public Renderer damageIndicatorRenderer;
    
        ....
    
        void DamageDone()
        {
            damageIndicatorRenderer.material = damageMat;
        }
    }