Home > Software design >  Can't change color of the material, Unity
Can't change color of the material, Unity

Time:05-01

First of all , i'm following an Unity C# tutorial on youtube and I'm stuggling to see why my code is not working, basically I'm using a script with "void OnCollisionEnter(Collision collision) to just change gameObject material color to red , but is not showing the change nor showing an error, my object (a sphere) has a rigidbody and the material I'm using on it has a standar shader and it's rendering mode it's opaque and I made it blue

the code I'm using on it's script:

void OnCollisionEnter(Collision collision)
{
    gameObject.GetComponent<Renderer>().material.color = Color.red;
 }

and it does nothing, tried changing the shader , the color on the code and I still have no idea why isn't changing on Unity

CodePudding user response:

Are you sure the method is being called? OnCollisionEnter is triggered when this collider/rigidbody has started contact with another rigidbody/collider.

Check that there is a collider/rigidbody on the object that the sphere collides with and on the sphere itself

Also, try using Debug.Log() to make sure that the code is triggered.

I checked your line in the Start() method, it works. The problem is something else

CodePudding user response:

First make sure it runs within the function. Use Debug.Log () for this purpose. Use this if the function performs correctly.

private void OnCollisionEnter(Collision collision)
{
    Debug.Log("On Collision Enter: "  collision.gameObject.name);
    
    GetComponent<MeshRenderer>().material.color = Color.red;
}
  • Related