Home Coding, Scripting, Shaders

unity material change after collision not working

privateunlimited
polycounter lvl 2
Offline / Send Message
Pinned
privateunlimited polycounter lvl 2
A little prototype I am making for my game, where the player's material should change when colliding with the white object.

gameObject.GetComponent<Renderer>().material = newMaterial;


This code is not working, I even tried to use this code at the start just to check if this works but doesn't.
 I have made sure to assign the newMaterial in Unity.
 I also tried changing color using
gameObject.GetComponent<Renderer>().material.color = newMaterial.color;

but this also seems to not be having any effect on the player's color.

Replies

  • Finnn
    Offline / Send Message
    Finnn greentooth

    Not sure if you still need help, but I suggest you set a breakpoint in that line and check if the GetComponent actually finds your Renderer Component. My first guess would be, that it cant find it.

    It would also be helpful to see a full example of your code, because the problem may lay somewhere else.

    You can also try to execute this script on your game object and to see if there is something wrong with the components you assigned to your game object from inside the unity editor.

    using UnityEngine;
    using System.Collections;
    
    public class ExampleClass : MonoBehaviour
    {
        Material m_Material;
    
        void Start()
        {
            //Fetch the Material from the Renderer of the GameObject
            m_Material = GetComponent<Renderer>().material;
            print("Materials " + Resources.FindObjectsOfTypeAll(typeof(Material)).Length);
        }
    
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.A))
            {
                //Output the amount of materials before GameObject is destroyed
                print("Materials " + Resources.FindObjectsOfTypeAll(typeof(Material)).Length);
                //Destroy GameObject
                Destroy(gameObject);
            }
        }
    
        void OnMouseOver()
        {
            // Change the Color of the GameObject when the mouse hovers over it
            m_Material.color = Color.red;
        }
    
        void OnMouseExit()
        {
            //Change the Color back to white when the mouse exits the GameObject
            m_Material.color = Color.white;
        }
    
        void OnDestroy()
        {
            //Destroy the instance
            Destroy(m_Material);
            //Output the amount of materials to show if the instance was deleted
            print("Materials " + Resources.FindObjectsOfTypeAll(typeof(Material)).Length);
        }
    }
    
Sign In or Register to comment.