ar_tourism_flutter_unity/lib/unity_controller.dart
2025-05-14 18:24:12 +08:00

65 lines
1.7 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:flutter/services.dart';
/// Unity控制器用于Flutter与Unity之间的通信
class UnityController {
// 通信通道
static const MethodChannel _channel = MethodChannel('com.yourcompany.unity_flutter/unity');
// 单例实例
static final UnityController _instance = UnityController._internal();
// 工厂构造函数
factory UnityController() {
return _instance;
}
// 内部构造函数
UnityController._internal();
/// 打开Unity场景
/// [sceneName] Unity场景名称
Future<bool> openUnityScene(String sceneName) async {
try {
final bool result = await _channel.invokeMethod('openUnity', {
'sceneName': sceneName,
});
return result;
} on PlatformException catch (e) {
print('打开Unity场景失败: ${e.message}');
return false;
}
}
/// 关闭Unity
Future<bool> closeUnity() async {
try {
final bool result = await _channel.invokeMethod('closeUnity');
return result;
} on PlatformException catch (e) {
print('关闭Unity失败: ${e.message}');
return false;
}
}
/// 向Unity发送消息
/// [gameObject] Unity中的游戏对象名称
/// [methodName] 要调用的方法名
/// [message] 要发送的消息内容
Future<bool> sendMessageToUnity({
required String gameObject,
required String methodName,
required String message,
}) async {
try {
final bool result = await _channel.invokeMethod('sendMessageToUnity', {
'gameObject': gameObject,
'methodName': methodName,
'message': message,
});
return result;
} on PlatformException catch (e) {
print('向Unity发送消息失败: ${e.message}');
return false;
}
}
}