0
\$\begingroup\$

I am adding point lights in my scene ( max 6 ) and I want to be able to enable its Halo property via script. However in the documentation reference, they haven't mentioned how to enable the halo property of a light source via script.

This is what I have so far.

GameObject lightObj = new GameObject("Light");
lightObj.AddComponent<Light>();
lightObj.light.color = Color.blue;
lightObj.transform.position = city.transform.position + new Vector3(-6.0f,0,0);

Point Lights have a property "Draw Halo" on the Inspector but how do I enable it via script?

\$\endgroup\$
1
\$\begingroup\$

From what I can tell from the Halo class documentation, lights do some magic behind the scenes to automatically create a Halo component, but hide it from the hierarchy (much like how AudioSource.PlayOneShot() will automatically create and destroy new AudioSources while hiding them from the hierarchy). It seems the Halo component is not exposed. However, there is a workaround.

In my tests (using Unity 4.5.5) using the answers found in this Unity forum thread, I could not access the automatically created Halo via script, but if I added the Halo component to the light manually (Component -> Effects -> Halo) then I could access it via script according to the answer given by Thundergod44, which I'll quote (with minor modifications) below:

//It's possible with C# and System.Reflection:

var haloComponent = lightObj.GetComponent("Halo");
var haloEnabledProperty = haloComponent.GetType().GetProperty("enabled");
haloEnabledProperty.SetValue(haloComponent, enable, null);

You'll need to replace "enable" in that last line above with a boolean value. Enabled is true, disabled is false.

Admittedly, I'm pretty inexperienced with lights/halos and reflection, so you may have better luck getting things to work with the automatically created Halo component than I did. But I can confirm that manually adding a Halo component will allow you to work around this seeming oversight by Unity to expose the Halo component.

A tangential fact that I found to be an interesting explanation as to why I couldn't figure out how to add a Halo component via script is that GetComponent("Halo").GetType() returns Behaviour. That's a type I'd never seen before. You'll need to know this if you wish to use strong typing when declaring variables or getting the component. e.g.:

Behaviour haloComponent;

void Awake() {
    haloComponent = (Behaviour)lightObj.GetComponent("Halo");
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.