Search code examples
androidiosunity-game-enginewebcamautofocus

Unity3D Webcam Autofocus Callback?


I want to take a picture from camera using Unity. Taking picture itself is not a big deal but I want more accurate one using autofocus callback method like in Android (onAutoFocus(boolean success, Camera camera)) So I can take a picture if callback returns success true. Is there any way to do it in Unity or I need some plugin for that? If there is one can somebody reference to it? Thanks a lot!


Solution

  • There is a plugin called Camera Capture Kit available on the assetstore that seems to be able to do what you want. We used the code to make theese features available on both Android as well as iPhone.

        https://www.assetstore.unity3d.com/en/#!/content/56673
    

    Camera Capture Kit comes with a plug-n-play camera app which enables Auto-focus - you can set the autofocus mode by calling .

    CameraCapture.UnitySetFocusMode( webCamTextureReferance, FocusModes.Autofocus );
    

    That will represent AVCaptureFocusModeAutoFocus and you should be able to trigger a callback for the focus event yourself by adding a piece of code like this in the function initCapture in the file Assets/Tastybits/Native/iOS/CameraCapture.mm :

    [camDevice addObserver:self forKeyPath:@"adjustingFocus" options:flags context:nil];
    

    Now, Camera Capture Kit doesn't give you a callback when focus is being done on iOS so you will have to add it yourself and calling back to unity yourself using SendMessage.

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if( [keyPath isEqualToString:@"adjustingFocus"] ){
        BOOL adjustingFocus = [ [change objectForKey:NSKeyValueChangeNewKey] isEqualToNumber:[NSNumber numberWithInt:1] ];
        NSLog(@"Is adjusting focus? %@", adjustingFocus ? @"YES" : @"NO" );
        if(adjustingFocus)
          UnitySendMessage( "FocusController", "FocusChanged", "1" );
        else 
          UnitySendMessage( "FocusController", "FocusChanged", "0" );
    }}