Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

C# i can't disable light !

Discussion in 'Scripting' started by iazlur2, Sep 24, 2016.

  1. iazlur2

    iazlur2

    Joined:
    Sep 24, 2016
    Posts:
    6
    help:

    using UnityEngine;
    using System.Collections;

    public class lampetorche : MonoBehaviour {

    void Update ()
    {
    bool LampeActive = parchemin.LampeActive;
    if (LampeActive)
    {
    GetComponent<UnityEngine.Light>().enabled = true;
    }
    else
    {
    GetComponent<UnityEngine.Light>().enabled = false;
    }
    }
    }

    That not working ! :(
    ive test all solution, no one work...
     
  2. iazlur2

    iazlur2

    Joined:
    Sep 24, 2016
    Posts:
    6
    lol ive forgot to slip the script... x)
     
  3. SirNiklas

    SirNiklas

    Joined:
    Jun 7, 2015
    Posts:
    85
    Use coding tags for code snippets so that they are formatted and syntax-highlighted.

    I do not see any thinking errors in your script, so I can only guess that your local boolean LampeActive might not change its value over time. I need to see the parchemin class code to check that though.

    On top, I recognize some novice programming mistakes in the source provided. First, it would be easier if you had a method in lampetorche which sets the light component to either enabled or disabled, something like SetLightState. Now whenever the boolean LampeActive in parchemin would normally change its value, instead call the lampetorche class method SetLightState. This is more straightforward than checking every frame if a boolean in another script is either true or false.
    Code (CSharp):
    1. public void SetLightState(bool state)
    2. {
    3.    GetComponent<Light>().enabled = state;
    4. }
    Second mistake is your use of GetComponent. Every frame you will have to call this method which makes Unity search the components attached to the respective object and take out the right one. Rather, you should add a field to the lampetorche class of type Light and drag the Light component on the same object onto this field in the Unity inspector.
    Now you can use this reference to directly modify the enabled property.
    The whole script would now look like this:
    Code (CSharp):
    1. public class lampetorche : MonoBehaviour
    2. {
    3.    [SerializeField] // Makes this field visible in the inspector, although its private
    4.    private Light light;
    5.  
    6.    public void SetLightState(bool state)
    7.    {
    8.       light.enabled = state;
    9.    }
    10. }