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();
}
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;
}
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 ?
AndroidJavaObject camera=null;
AndroidJavaObject cameraParameters=null;
void ToggleAndroidFlashlight()
{
if (camera == null)
{
AndroidJavaClass cameraClass = new AndroidJavaClass("android.hardware.Camera");
camera = cameraClass.CallStatic<AndroidJavaObject>("open", 0);
if (camera != null)
{
cameraParameters = camera.Call<AndroidJavaObject>("getParameters");
cameraParameters.Call("setFlashMode","torch");
camera.Call("setParameters",cameraParameters);
}
}
else
{
cameraParameters = camera.Call<AndroidJavaObject>("getParameters");
string flashmode = cameraParameters.Call<string>("getFlashMode");
if(flashmode!="torch")
cameraParameters.Call("setFlashMode","torch");
else
cameraParameters.Call("setFlashMode","off");
camera.Call("setParameters",cameraParameters);
}
}
void ReleaseAndroidJavaObjects()
{
if (camera != null)
{
camera.Call("release");
camera = null;
}
}
Related
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();
}
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;
}
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 ?
AndroidJavaObject camera=null;
AndroidJavaObject cameraParameters=null;
void ToggleAndroidFlashlight()
{
if (camera == null)
{
AndroidJavaClass cameraClass = new AndroidJavaClass("android.hardware.Camera");
camera = cameraClass.CallStatic<AndroidJavaObject>("open", 0);
if (camera != null)
{
cameraParameters = camera.Call<AndroidJavaObject>("getParameters");
cameraParameters.Call("setFlashMode","torch");
camera.Call("setParameters",cameraParameters);
}
}
else
{
cameraParameters = camera.Call<AndroidJavaObject>("getParameters");
string flashmode = cameraParameters.Call<string>("getFlashMode");
if(flashmode!="torch")
cameraParameters.Call("setFlashMode","torch");
else
cameraParameters.Call("setFlashMode","off");
camera.Call("setParameters",cameraParameters);
}
}
void ReleaseAndroidJavaObjects()
{
if (camera != null)
{
camera.Call("release");
camera = null;
}
}
I am implementing an user reporting function, trying to give user the ability to post picture to their report. Here the code:
public class ResponseImageHandler : MonoBehaviour
{
[SerializeField] GameObject[] imgHolder;
[SerializeField] Texture2D defaultTexture;
[SerializeField] TMP_Text imgIndicator;
Texture2D tempTexture;
int curIdx = 0;
void Start()
{
for (int i = 0; i < 4; i++)
{
imgHolder[i].transform.GetChild(0).gameObject.AddComponent<ButtonIndex>();
imgHolder[i].transform.GetChild(0).gameObject.GetComponent<ButtonIndex>().Init(i + 1);
imgHolder[i].GetComponent<Button>().interactable = true;
imgHolder[i].GetComponent<Button>().onClick.AddListener(ChoosePictureOnClick);
}
}
void ChoosePictureOnClick()
{
ChoosePicture(SystemInfo.maxTextureSize);
}
void ChoosePicture(int maxSize)
{
NativeGallery.Permission permission = NativeGallery.GetImageFromGallery((path) =>
{
if (path != null)
{
tempTexture = NativeGallery.LoadImageAtPath(path, maxSize, false);
if (tempTexture == null)
{
Debug.Log($"cant load image from path: {path}");
return;
}
else
{
imgHolder[curIdx].GetComponent<Button>().interactable = false;
imgHolder[curIdx].transform.GetChild(0).gameObject.SetActive(true);
imgHolder[curIdx].GetComponent<RawImage>().texture = tempTexture;
if (curIdx < 3)
{
curIdx++;
}
imgIndicator.text = $"{curIdx}/4";
}
}
});
imgHolder[curIdx].SetActive(true);
}
In Unity editor, i was able to insert all 3 slot with picture and an empty slot
Unity Editor
But in Android Studio Emulator and also on android device, i can only insert one picture and then no further slot appear to insert more picture
Android Studio Emulator
I have no idea what happen can any one give me an explanation? And how to fix the problem?
I'm using Unity 2021.3.5f1 version and NativeGallery asset to get picture from device.
So I'm trying to mute a specific audio source once my death menu pops up ingame. I tried with:
public void toggleEndMenu(float score)
{
GameObject jumpGameObject = GameObject.Find("Jump");
if (jumpGameObject != null)
{
AudioSource jumpAudio = jumpGameObject.GetComponent<AudioSource>();
if (jumpAudio != null)
{
jumpAudio.mute = true;
}
}
gameObject.SetActive(true);
scoreText.text = ((int)score).ToString();
isShown = true;
This did not work the audiosource does not get muted, maybe it cannot find the gameobject or something?
I am trying to draw a line from camera to a instantiated object.I am using the scene UnityARHitTest Example.When I touch on a vertical plane the object gets instantiated and i want to draw a line from camera to the object.When I move my device the line should show from the centre of my camera.For some reason line renderer is not showing when I call it in the Late update.
LineRenderer lins;
public GameObject Lineprefab;
bool HitTestWithResultType (ARPoint point, ARHitTestResultType resultTypes)
{
List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface ().HitTest (point, resultTypes);
if (hitResults.Count > 0 && check==true)
{
foreach (var hitResult in hitResults)
{
Debug.Log ("Got hit!");
if (Select == 0)
{
Debug.Log("hit-zero!");
Instantiate(Instaobj[0], ForSelect);
check = false;
}
if (Select == 1)
{
Debug.Log("hit-one!");
Instantiate(Instaobj[1], ForSelect);
check = false;
}
if (Select == 2)
{
Debug.Log("hit-two!");
Instantiate(Instaobj[2], ForSelect);
check = false;
}
if (Select == 3)
{
Debug.Log("hit-three!");
Instantiate(Instaobj[3], ForSelect);
check = false;
}
if (Select == 4)
{
Debug.Log("hit-four!");
Instantiate(Instaobj[4], ForSelect);
check = false;
}
if (Select == 5)
{
Debug.Log("hit-five!");
Instantiate(Instaobj[5], ForSelect);
check = false;
}
m_HitTransform.position = UnityARMatrixOps.GetPosition (hitResult.worldTransform);
m_HitTransform.rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform);
Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
obj.StopPlaneTracking();
if (GameObject.Find("debugPlanePrefab(Clone)"))
GameObject.Find("debugPlanePrefab(Clone)").SetActive(false);
else
Debug.Log("no prefab");
//lins.SetPosition(0, m_HitTransform.position);
//lins.SetPosition(1, obj.m_camera.transform.position);
return true;
}
}
return false;
}
When I use lins.setposition() in the above method(which is commented) a line is shown in the output.When I use lins.setposition() in the below LateUpdate() the output is not shown nothing comes.
private void Start()
{
spawngenerator();
}
void spawngenerator()
{
GameObject newline = Instantiate(Lineprefab);
lins = newline.GetComponent<LineRenderer>();
//lins.SetPosition(0, m_HitTransform.position);
//lins.SetPosition(1, obj.m_camera.transform.position);
}
private void LateUpdate()
{
lins.SetPosition(0,obj.m_camera.transform.position );
lins.SetPosition(1,m_HitTransform.position );
}
I want to make a Xamarin.iOS app where I can capture pictures like the camera... My app supports only portrait.
I want to turn the captured picture to portrait if the camera was landscape when i capture the picture.
Does someone know how I can do this?
Code
public async void CapturePhoto()
{
var videoConnection = stillImageOutput.ConnectionFromMediaType(AVMediaType.Video);
var sampleBuffer = await stillImageOutput.CaptureStillImageTaskAsync(videoConnection);
var jpegImageAsBytes = AVCaptureStillImageOutput.JpegStillToNSData(sampleBuffer).ToArray();
string base64StringImage = Convert.ToBase64String(jpegImageAsBytes);
FaceRecognition faceRecognition = new FaceRecognition();
int result = faceRecognition.SendPhoto(base64StringImage);
}
Try this :
var currentOrientation = UIApplication.SharedApplication.StatusBarOrientation;
if (currentOrientation == UIInterfaceOrientation.Portrait)
{
videoConnection.VideoOrientation = AVCaptureVideoOrientation.Portrait;
}
else if (currentOrientation == UIInterfaceOrientation.LandscapeRight)
{
videoConnection.VideoOrientation = AVCaptureVideoOrientation.LandscapeRight;
}
//xxx
Update:
If the app only supports an orientation or you lock the screen , there is another old way to detect device orientation. Core Motion
public void LockOrientation()
{
CMMotionManager CMManager = new CMMotionManager();
CMManager.DeviceMotionUpdateInterval = 0.2f;
CMManager.StartDeviceMotionUpdates(NSOperationQueue.MainQueue, (motion, error) => {
if (Math.Abs(motion.Gravity.X) > Math.Abs(motion.Gravity.Y))
{
Console.WriteLine("Lan");
if (motion.Gravity.X > 0)
{
UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.LandscapeLeft), new NSString("orientation"));
Console.WriteLine("Left");
}
else
{
UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.LandscapeRight), new NSString("orientation"));
Console.WriteLine("Right");
}
}
else
{
if (motion.Gravity.Y >= 0)
{
Console.WriteLine("Down");
}
else
{
Console.WriteLine("UP");
}
}
CMManager.StopDeviceMotionUpdates();
});
}
Refer to here