- Home /
GetComponent() returns the outline text effect instead of the shadow text effect!
Basically I'm using both an outline (Outline) and a shadow (Shadow) on my UI.Text. When I try to fade both the shadow and the outline I use:
Shadow shadow = GetComponent<Shadow>();
Outline outline = GetComponent<Outline>();
Those lines will make both the shadow variable and the outline variable bound to the SAME Outline component in the game object! How do I fetch the shadow component?
2018.3.0f2 It is indeed the issue, If a component is having "Shadow" and "Outline" both. The GetComponent is returning "Outline" is case of "shadow".
Answer by Bunny83 · Mar 03, 2020 at 10:12 AM
Well, that is a common issue when inheritance is used. The Outline class is actually derived from the Shadow class. So an Outline actually is also a Shadow. Therefore GetComponent<Shadow>()
will face two instances on the same object. As far as I remember Unity now searches through the components in the same order they appear in the inspector. So a "hacky" solution is to swap the order of the two components in the inspector. That should fix the issue, though not in a nice way.
The best and most robust solution is: Do not use GetComponent but assign the reference through the inspector. If that's not possible for some reason to make the code more robust you would need to use GetComponents<Shadow>()
(note the plural), iterate through the components and filter out the right components by doing some type checks.
Shadow shadow;
Outline outline;
foreach(var c in GetComponents<Shadow>())
{
Outline o = c as Outline;
if (o == null) // component is not an Outline
shadow = c;
else // component is an Outline
outline = o;
}
That doesn't really look very nice but will work no matter what order the two components have.
Answer by shadowwwww · Mar 28, 2018 at 08:29 AM
is this U need?
public GameObject Outline;
Outline.GetComponent<Outline>().effectDistance = new Vector2(3, 3);
Outline.GetComponent<Outline>().effectColor = Color.black;
No Dear, Consider reading the question again, and you will see the "shadow" part.
Your answer

Follow this Question
Related Questions
Deferred Rendering lighting bug. 0 Answers
Light/Shadow Z-Fighting Styled Flickering while Camera is Moving Around 2 Answers
Unity pro 4, shadow problems 0 Answers
Terrain flickering, really annoying please help 6 Answers
Why won't shadows render? 1 Answer