Enable Phone Flashlight from Game in Unity

In this tutorial, we'll explore how to control the flashlight (torch) on a mobile device directly from a Unity game using platform-specific APIs through plugins. This functionality can enhance gameplay immersion or provide utility within your app.

Setup

Before diving into code, ensure you have a mobile device with a flashlight (most smartphones have this feature). Also, make sure you have Unity installed and a basic understanding of C# scripting.

Implementation Steps

Step 1: Create a Native Plugin

We'll create a native plugin for both iOS and Android to access their respective flashlight APIs.

For Android (Java)

Create a Java class that interacts with the Android flashlight API.

package com.example.flashlight;

import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;

public class Flashlight {

    private Context context;
    private CameraManager cameraManager;
    private String cameraId;

    public Flashlight(Context context) {
        this.context = context;
        cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        try {
            cameraId = cameraManager.getCameraIdList()[0];
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    public void enableFlashlight() {
        try {
            cameraManager.setTorchMode(cameraId, true);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    public void disableFlashlight() {
        try {
            cameraManager.setTorchMode(cameraId, false);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
}
For iOS (Objective-C/Swift)

Create an Objective-C or Swift class that interacts with the iOS flashlight API.

#import <AVFoundation/AVFoundation.h>

@interface Flashlight : NSObject

- (void)enableFlashlight;
- (void)disableFlashlight;

@end

@implementation Flashlight

- (void)enableFlashlight {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch] && [device isTorchAvailable]) {
        [device lockForConfiguration:nil];
        [device setTorchMode:AVCaptureTorchModeOn];
        [device unlockForConfiguration];
    }
}

- (void)disableFlashlight {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        [device setTorchMode:AVCaptureTorchModeOff];
        [device unlockForConfiguration];
    }
}

@end

Step 2: Unity C# Scripting

Create a C# script in Unity to call these native functions using platform-specific conditional compilation.

using UnityEngine;

public class FlashlightController : MonoBehaviour
{
    private static Flashlight flashlight;

    void Start()
    {
        flashlight = new Flashlight();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            ToggleFlashlight();
        }
    }

    void ToggleFlashlight()
    {
        if (IsFlashlightOn())
        {
            flashlight.DisableFlashlight();
        }
        else
        {
            flashlight.EnableFlashlight();
        }
    }

    bool IsFlashlightOn()
    {
        // Implement check for flashlight state based on platform-specific logic
        return false;
    }
}

Step 3: Integration and Testing

Attach the FlashlightController script to a GameObject in your Unity scene. Test the functionality by pressing the designated key (in this case, 'F') to toggle the flashlight on and off. Ensure to build and deploy the native plugins to your target devices.

Conclusion

You've now learned how to control the flashlight on a mobile device directly from within a Unity game using platform-specific APIs through plugins. This approach allows you to integrate device-specific features seamlessly into your Unity projects, enhancing both gameplay and utility for your users.

Links
Unity