Changing Cube's Color on Collision with Character Controller / C#

Hello Guys,

Another question as I progress with my learning coding in Unity. I have added:

  1. A plane
  2. Character Controller (Named ‘Matt’ in Hierarchy)
  3. A Cube (Which should change color to Red on keypress and also if Character Controller collides with the collider on cube) + The script is attached to the cube

I would like the CUBE to change it’s color if R key is pressed (which works) or if the player controller collides with the cube’s collider.


using UnityEngine;
using System.Collections;

public class colorChange : MonoBehaviour {

    public GameObject cube;
    private Renderer rend;

    // Use this for initialization
    void Start () {
       
    }
   
    // Update is called once per frame
    void Update () {
       
        // This will get the OBJECT to CHANGE COLOR on KEY PRESS
        if (Input.GetKeyDown (KeyCode.R))
            GetComponent<Renderer> ().material.color = Color.red;
            print ("A Key Pressed For Red Color");
    }

    void OnCollisionEnter (Collision col)
    {
        if (col.collider.name == "Matt")

        {
            rend.material.color = Color.yellow;
        }
    }
}

Thank you for your help :slight_smile:

Waqas

ok first thing, if you’re just starting out, use { } for all your if statements. line 20 is called every frame regardless since it’s outside of the single line scope of the if on line 18. Saving the occasional character in a script isn’t worth the mess you can get into by missing something like that.

you should be getting a warning about rend never being private and never initialised at the very least, and probably a null ref error when you actually collide. line 19 access the renderer on the current gameobject directly. Line 28 access the reference that is never initialised. Either, make both use the getcomponent function, or initialise the reference “rend” in the start function and use the reference throughout.

1 Like

how do you change character in https://www.w3schools.com/code/tryit.asp?filename=GQ6KVZLBLWK7 I made some code not all though.