Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Why can't I use the "renderer"?

Discussion in 'Scripting' started by sebastianfeistl, Jun 3, 2016.

  1. sebastianfeistl

    sebastianfeistl

    Joined:
    Sep 29, 2015
    Posts:
    4
    I think I have a very obvious issue, but as a beginner C# programmer I still don't get it:

    I have a simple cube named "MyCube" and furthermore I have a material called "MyMaterial". I am trying to assign the material to the cube using a script (which is attached to the cube). As far as I know that should work like this:

    Code (CSharp):
    1. gameObject.renderer.material = newMat;
    (in my case instead of "gameObject" I use the cube)

    So as you can see in my attached screenshot MonoDevelope just crosses it out and I can't use it, but why is that so and how can I do it right?

    unity_screenshot.jpg
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,196
    gameObject.renderer used to be around in Unity 4 and earlier. It was a terrible idea - if there wasn't a renderer attached, things would just break.

    It's still around, but deprecated (the line through it), to inform developers that moved code from Unity 4 to Unity 5 that their code needed to change.

    The way you do this now is to get the Renderer component with the GetComponent call:

    Code (csharp):
    1. gameObject.GetComponent<Renderer>().material = newMat
     
    sebastianfeistl likes this.
  3. Steve-Tack

    Steve-Tack

    Joined:
    Mar 12, 2013
    Posts:
    1,240
    You can't do that any more. You have to explicitly call GetComponent to get a component (other than Transform). So instead of that line, so something like:

    Renderer myRenderer = go.GetComponent<Renderer>();
    myRenderer.material = newMat;

    EDIT: Hehe, @Baste, beat me to it. :)
     
    sebastianfeistl likes this.
  4. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,196
    Too slow, too slow.
     
  5. sebastianfeistl

    sebastianfeistl

    Joined:
    Sep 29, 2015
    Posts:
    4
    Well, thank you both for the quick reply :)