How turn On/Off android flashlight using C# only in Unity3d
Solution 1
Newer Samsung phones are very picky about code.
You need to use camera1.Call("startPreview");
as shown below;
if (camera1 != null)
{
AndroidJavaObject cameraParameters = camera1.Call<AndroidJavaObject>("getParameters");
cameraParameters.Call("setFlashMode", "torch");
camera1.Call("setParameters", cameraParameters);
///FIX/////
camera1.Call("startPreview");
Active = true;
}
Solution 2
You could have a look at the Android plugin source for Camera Capture Kit (https://www.assetstore.unity3d.com/en/#!/content/56673) - I know you said you don't like plugins however with this one the source is availble and lets you see what goes on for you to tweak. With regards to your problem, Not all phones have the Torch functionality so that might be what you should check for for that ? Maybe you sohuld use the referance that unity itself is using ?
asker22
Updated on June 13, 2022Comments
-
asker22 almost 2 years
Anybody knows how to turn On/Off android flashlight using C# only in Unity? I don't like plugins, and I don't want to make one of my own. Is there a why to make my device switch the flashlight On or Off using pure C#?
I tried to add this script to the main camera, but it just didn't do the trick :(
private bool Active; private AndroidJavaObject camera1; void FL_Start() { AndroidJavaClass cameraClass = new AndroidJavaClass("android.hardware.Camera"); WebCamDevice[] devices = WebCamTexture.devices; int camID = 0; camera1 = cameraClass.CallStatic<AndroidJavaObject>("open", camID); if (camera1 != null) { AndroidJavaObject cameraParameters = camera1.Call<AndroidJavaObject>("getParameters"); cameraParameters.Call("setFlashMode", "torch"); camera1.Call("setParameters", cameraParameters); Active = true; } else { Debug.LogError("[CameraParametersAndroid] Camera not available"); } } void OnDestroy() { FL_Stop(); } void FL_Stop() { if (camera1 != null) { camera1.Call("stopPreview"); camera1.Call("release"); Active = false; } else { Debug.LogError("[CameraParametersAndroid] Camera not available"); } } void OnGUI() { GUILayout.BeginArea(new Rect(Screen.width * 0.1f, Screen.height * 0.1f, Screen.width * 0.3f, Screen.height * 0.1f)); if (!Active) { if (GUILayout.Button("ENABLE FLASHLIGHT")) FL_Start(); } else { if (GUILayout.Button("DISABLE FLASHLIGHT")) FL_Stop(); } GUILayout.EndArea(); }
-
asker22 about 9 yearsThank you so much! one of the coolest answers I ever saw on StackOverFlow. Will this code work for all devices or only Samsung devices?