1
\$\begingroup\$

I'm using a gradient script to change the color of a sphere over time, but I want a point light associated to it to change too.

The script I'm using is this:

public class gradient : MonoBehaviour
{
    public Gradient myGradient;
    public float strobeDuration = 2f;

    public void Update()
    {
        float t = Mathf.PingPong(Time.time / strobeDuration, 1f);
        GetComponent<Renderer>().material.color= myGradient.Evaluate(t);
    }
}

The light object accepts the script but it doesn't affect the color.

I assume it's because this script is associated to materials and light has no material...

\$\endgroup\$
3
  • 3
    \$\begingroup\$ Your assumption sounds sensible. So, based on that assumption, you tried modifying the script to get the Light component instead of the Renderer component, and assign the light's colour that way? \$\endgroup\$
    – DMGregory
    Commented Jul 13, 2021 at 19:01
  • 3
    \$\begingroup\$ You can usually find answers to this type of questions by doing a web search for things like 'unity change color of light from code'. \$\endgroup\$
    – Kevin
    Commented Jul 13, 2021 at 19:36
  • \$\begingroup\$ Thanks for your answers, i asjed here after searching in tutorials on utube and in this forum for similar questions but dont seem to find the right answer. Any ways i will keep looking, thanks \$\endgroup\$ Commented Aug 25, 2021 at 12:05

1 Answer 1

3
\$\begingroup\$

Your light's color isn't changing because it uses the Light component, not Renderer. Simply add support for the Light component:

if (TryGetComponent(out Light light))
    light.color = myGradient.Evaluate(t);

With that said, I'd recommend that you use TryGetComponent for working with the Renderer component too:

if (TryGetComponent(out Renderer renderer))
    renderer.material.color = myGradient.Evaluate(t);

The use of TryGetComponent will help prevent potential NullReferenceExceptions from occurring.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .