- Home /
How to fade out an object with no renderer (and how is that even possible?!)
Noob here, cribbing from other scripts, I see that I can do...
target.renderer.material.color.a -= Time.deltaTime/fadeDuration;
to fade out an object. And, elsewhere in the docs, I see that EVERYTHING YOU SEE ON SCREEN has a renderer that you can enable = true/false to show/hide it. Ok... but the above line gives me "renderer is not a component of GameObject" error. So, being resourceful, I think...
var target : GameObject; var targetRenderer : Renderer;
function Start() { targetRenderer = target.GetComponent(Renderer); if (targetRenderer == null) targetRenderer = target.GetComponentInChildren(Renderer); }
function Update() { if (targetRenderer.material.color.a > 0) targetRenderer.material.color.a -= Time.deltaTime/fadeDuration; }
but then I get "trying to access Renderer on GameObject when there is none." What gives? What am I missing?! If it's on-screen, it's got to have a renderer, right?!
Thanks!
P.S. All I really want to do is make my object fade out before removing him from the scene, like in TonyD's script, here.
Answer by Eric5h5 · Mar 26, 2010 at 05:20 AM
The first line of code you wrote is fine, but you haven't given enough info about how you're defining variables. For example, this works with no issues, assuming the target object actually has a renderer:
var target : GameObject;
function Update () { target.renderer.material.color.a -= Time.deltaTime/fadeDuration; }
But a GameObject doesn't necessarily have a renderer. The only required component is a Transform. If you're trying to access a renderer component of a child GameObject where no renderer component exists, then you will get the error message you quoted.
Ok, but, as I understand the docs, if I can see something on the screen, it's got a renderer, right? So if I check the original gameObject's render and it's null, I should check the children, right? And, if it's on-screen, one of those two things should have a renderer, right?! In my test case, the object I'm using is the copperDeadPrefab from the 3d-platformer tutorial.
I've updated the questions's code sample to be more explicit about what I'm trying-and-failing. The target GameObject is an object I can see in the scene. The error message appears to be telling me that it doesn't have a renderer, which is counter-intuitive to me. I'm trying to figure out if I mis-understand the error msg or if I misunderstand "everything you see has a renderer" (or both :D)
@Olie: if you get a message saying an object doesn't have a renderer, then the particular object you are referencing does not have a renderer. So you may not be accessing the object you intended to access. BTW, an object can be visible without a renderer, such as a GUITexture. The only way to tell for sure is to look at the object and see if it has a renderer component.