Usage of GetComponent<>();

Hi, so I have been working in unity and I have the need to enable / change intensity of lights with a collider trigger setup.

My script is as follows

Public Light BridgeLight;

Then i get that component

Then in the “on trigger enter” i have the light.intensity

This code works, however when i apply the script to my trigger cube, i drag the light i want to reference into the “public Light” to reference it in the UI under the script, however whenever the game runs it removes all the lights from the fields. I know the code works because if i drag the lights into the public Light boxes while its running it functions as expected. Is this a bug, or is there some part of my script or setting i need to change to retain the light game objects. I have used this same code in other applications (not triggers) and it does not remove the lights, only when “is trigger” is checked. I have searched for about an hour to no avail so im not aware of anyone else asking this question(sorry).

Any insight isngreatly appreciated, thanks!

Avin

Bump

Im Running out of time.

Post code, and use code tags.

using UnityEngine;

public class ExampleClass : MonoBehaviour {
      
       public Light BridgeLight; //This creates the field in the editor where the light wont stay.
}

       void Start (); {
              BridgeLight = GetComponent<Light>();
}

       void OnTriggerEnter(Collider other) {
              BridgeLight.Intensity = 4;
}

When you drag the light into the “Public Light BridgeLight;” in the editor, in the scripts box (The script is attached to the trigger) the lights will stay until runtime, then that field is cleared until i stop the game, then they come back. if i drag the lights in AFTER the game is running, the code works flawlessly.

So you drag a component into a field outside of play mode, then run the game and tell it “As soon as you Start(), override this field with a GetComponent call that probably doesn’t even find a component so its going to be null”. Then you get an empty field as soon as things start up and are confused why it works when you drag it over to assign the field manually?

I mean, think about it for more than 2 seconds and it’s pretty clear.

Oh, ok thank you i was misunderstanding the GetComponent; i now know what you mean, thanks.

1 Like

Read the API if you don’t understand what something does instead of arbitrarily adding broken code.

You can also check the tutorial section which has a nice pace and explains all of the basics to all the major Unity systems.

Please don’t ask for the thread to be deleted. People may have the same problem as you in the future and find this thread useful.

So if you can rename the thread that would be great :wink: