javac#androidunity-game-enginelight-sensor

I'm trying to get light sensor data from an Android device for use in a Unity app


Preface: There is a post made in 2016 by Ice-Blaze that covers this, his solution no longer works.

I've tried using his plugin and it does not seem to pass data or retrieve light sensor data. In that process I built out my own plugin in the form of a .aar/Android Library, for whatever the reason I can pass predefined static data from the .aar to the Unity app but not successfully retrieve light data. I believe this has to do with retrieving the light data requiring a base App-Activity and I'm not sure how to build it out for a .aar instead of a .apk.

So now I've moved on to trying to work strictly in Unity and skipping the plugin altogether. Right now this is what my Update function looks like:

Update()
 {
    InputSystem.DisableDevice(LightSensor.current);
    InputSystem.EnableDevice(LightSensor.current);

        if (LightSensor.current.enabled)
        {
            var CurrentLight = LightSensor.current.samplingFrequency;
            DisplayLight = (float)CurrentLight;
        }
        Light.value = (float)DisplayLight;
}

So here you can see that on every update I disable the device only to re-enable it. The reason I went that route is because this seems to only getting light data once on start so I thought that disabling/re-enabling might force it to consistently recheck the light value. Right now I get an initial value of 50 and no updating, it's possible that that 50 could be a default value though as I've tried under different brightness and always get the same result. Does anyone have any suggestions or fixes?


Solution

  • Here's the fix.

    Update()
     {
        InputSystem.DisableDevice(LightSensor.current);
        InputSystem.EnableDevice(LightSensor.current);
    
            if (LightSensor.current.enabled)
            {
                var CurrentLight = LightSensor.current.lightLevel.ReadValue(); // <= change here
                DisplayLight = (float)CurrentLight;
            }
            Light.value = (float)DisplayLight;
    }