Why can't I use the "renderer"?

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:

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?

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:

gameObject.GetComponent<Renderer>().material = newMat
1 Like

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();
myRenderer.material = newMat;

EDIT: Hehe, @Baste , beat me to it. :slight_smile:

1 Like

Too slow, too slow.

Well, thank you both for the quick reply :slight_smile: