Search Unity

Need Help Using C# To Active Multiple Objects with one Switch

Discussion in 'Scripting' started by bmorecareful6, Nov 21, 2019.

  1. bmorecareful6

    bmorecareful6

    Joined:
    Apr 24, 2016
    Posts:
    3
    What I am trying to do is use one Switch to turn multiple Light2d Using GameObject[]. Well It works but I get a Null Reference Object reference not set to an instance of object. The lights still get turned on even if they are not in the public array and that is not what I want. What I need is that one I jump on a switch it activates a bunch of lights (Light2D) that are in the public array with out the errors. Here is the code that I am using to try to accomplish this. I have tried so much and nothing works.


    Code (csharp):
    1. public class LightsOn : MonoBehaviour
    2. {
    3.     public GameObject lSwitch;
    4.     public GameObject[] lights;
    5.     void Start()
    6.     {
    7.         lights = GameObject.FindGameObjectsWithTag("LightToActivate");
    8.  
    9.      
    10.     }
    11.  
    12.     void Update()
    13.     {
    14.         LightIsOn();
    15.     }
    16.  
    17.     public void LightIsOn()
    18.     {
    19.         if (lSwitch.GetComponent<SwitchActivate>().isOn == true)
    20.         {
    21.             foreach (GameObject lights in lights)
    22.            {
    23.  
    24.                 lights.GetComponent<UnityEngine.Experimental.Rendering.LWRP.Light2D>().intensity = 1;
    25.             }
    26.  
    27.         }
    28.     }
    29. }
     
    Last edited: Nov 21, 2019
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
  3. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    Two things come to mind:

    Code (CSharp):
    1. foreach (GameObject lights in lights)
    You name both the GameObject an the Array 'lights'. Does that even compile? Make sure to name your variables carefully.

    In Editor, check if there is an empty 'slot' in your Array, i.e. the number of objects show for length the is greater than the number of objects you filled in. This can easily happen if you deleted an object that was previously in the array.
     
  4. bmorecareful6

    bmorecareful6

    Joined:
    Apr 24, 2016
    Posts:
    3
    It does work all of the lights light up when I step on the switch but I get a NullReferenceException: Object reference not set to an instance of an object. I have never used an array before like this.
     
  5. bmorecareful6

    bmorecareful6

    Joined:
    Apr 24, 2016
    Posts:
    3
    All slots are full I do not get it.
     
  6. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    GetComponent might return null if object is not active