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

    unity material change after collision not working

    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.

    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ExampleClass : MonoBehaviour
    5. {
    6. Material m_Material;
    7.  
    8. void Start()
    9. {
    10. //Fetch the Material from the Renderer of the GameObject
    11. m_Material = GetComponent<Renderer>().material;
    12. print("Materials " + Resources.FindObjectsOfTypeAll(typeof(Material)).Length);
    13. }
    14.  
    15. void Update()
    16. {
    17. if (Input.GetKeyDown(KeyCode.A))
    18. {
    19. //Output the amount of materials before GameObject is destroyed
    20. print("Materials " + Resources.FindObjectsOfTypeAll(typeof(Material)).Length);
    21. //Destroy GameObject
    22. Destroy(gameObject);
    23. }
    24. }
    25.  
    26. void OnMouseOver()
    27. {
    28. // Change the Color of the GameObject when the mouse hovers over it
    29. m_Material.color = Color.red;
    30. }
    31.  
    32. void OnMouseExit()
    33. {
    34. //Change the Color back to white when the mouse exits the GameObject
    35. m_Material.color = Color.white;
    36. }
    37.  
    38. void OnDestroy()
    39. {
    40. //Destroy the instance
    41. Destroy(m_Material);
    42. //Output the amount of materials to show if the instance was deleted
    43. print("Materials " + Resources.FindObjectsOfTypeAll(typeof(Material)).Length);
    44. }
    45. }
Sign In or Register to comment.