Integrar Unity 및 위치 키트
소개:
En este artículo, aprenderemos cómo integrar el kit de ubicación y obtener la última latitud y longitud de ubicación conocidas en unidad utilizando el Complemento Huawei HMS Core App Services.
요구 사항:
#산출:
Mostrar última latitud y longitud conocidas.
#고려사항:
Para las bibliotecas del kit de ubicación y connectión de App Gallery, usaremos una versión específica, verifique si hay una una versión más nueva disponible.
#파소스 파라 통합:
##Unity 프로젝트 생성
Abra Unity Hub와 cree un proyecto(en nuestro caso, un proyecto 2D). UnityLocationKit의 프로젝트 이름입니다.
Unity에서 Windows> Asset Store를 선택하고 HMS Core App Services에서 가져오기를 클릭하세요.

Cambiar plataforma: haga clic en Configuración de compilación, selectione Android y presione Cambiar plataforma.

Selecturación Configuración del reproductor> Configuración de publicación> Administrador de almacén de claves y cree un nuevo archivo de almacén de claves de la siguiente manera.


Actualice el nombre del paquete.
En Configuración del proyecto> Configuración de publicación, habilite las siguientes opciones.

En el terminal de la línea de comandos, ejecute el siguiente comando y obtenga la clave SHA:
keytool -list -v -keystore D:\yourpath\UnityLocationKit.keystore

AppGallery에서 프로젝트 구성 생성
AGC 콘솔을 탐색하고 새로운 프로젝트를 Unity의 잘못된 프로젝트로 확인하십시오(이 경우 UnityLocationKit).

통합 적용

Guarde la clave SHA en la consola AGC.
Habilitar el kit de ubicación

Descargue agconnect-services.json y cópielo en Assets> Plugins> Android in unity project.
HMS에 대한 종합 보완 및 종속성
En Manifiesto, agregue permisos de uso y etiqueta de servicio:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<receiver android:name="com.unity.hms.location.LocationBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="com.huawei.hmssample.location.LocationBroadcastReceiver.ACTION_PROCESS_LOCATION" />
</intent-filter>
</receiver>
<receiver android:name="com.unity.hms.location.GeoFenceBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="com.huawei.hmssample.geofence.GeoFenceBroadcastReceiver.ACTION_PROCESS_LOCATION" />
</intent-filter>
</receiver>
En LaucherTemplate agregue elcomplementoylasdependencias
apply plugin: 'com.huawei.agconnect'
implementation 'com.huawei.agconnect:agconnect-core:1.2.0.300'
implementation 'com.huawei.hms:location:5.0.0.302'
implementation 'com.android.support:appcompat-v7:28.0.0'
En MainTemplate agregue las 종속성:
implementation 'com.huawei.hms:location:5.0.0.302'
BaseProjectTemplate에서 agregue esto en los repositorios de buildscript y en todos los repositorios del proyecto y en la ruta de clases de App Gallery Connect.
maven { url 'https://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.2.1.301'
Debe 구절 así:
allprojects {
buildscript {
repositories {**ARTIFACTORYREPOSITORY**
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.0'
classpath 'com.huawei.agconnect:agcp:1.2.1.301'
**BUILD_SCRIPT_DEPS**
}
}
repositories {**ARTIFACTORYREPOSITORY**
google()
jcenter()
flatDir {
dirs "${project(':unityLibrary').projectDir}/libs"
}
maven { url 'https://developer.huawei.com/repo/' }
}
}
Vaya a Archivo> Configuración de compilación> Configuración del reproductor> Reproductor y actualice el nombre de la empresa y el nombre del paquete
게임 오브젝트 생성 및 코드화
Mostraremos la ubicación en un objeto de juego TEXT, haga clic en GameObject> UI> TEXT y cambiaremos el nombre del objeto creado a LocationText
GameObject를 클릭하고 GameObject> Create Empty를 클릭하여 LocationManagerGameObject의 개체 이름을 지정합니다.

Dentro de la carpeta de activos crear carpeta de script.
C# 스크립트는 LocationManager라는 이름으로 지정됩니다.
LocationManagerGameObject를 클릭하고 통합 구성요소를 클릭하고 LocationManager를 선택하는 스크립트를 클릭합니다.
Abrir 보안 명령은 LocationManager입니다.
Agregue la siguiente secuencia de comandos:
using HuaweiHms;
using System;
using UnityEngine;
using UnityEngine.Android;
using UnityEngine.UI;
using Exception = HuaweiHms.Exception;
public class LocationManager : MonoBehaviour
{
private static Text locationText;
private FusedLocationProviderClient mFusedLocationProviderClient;
public delegate void SuccessCallBack<T>(T o);
public delegate void FailureCallBack(Exception e);
public LocationRequest mLocationRequest;
void Start()
{
locationText = GameObject.Find("LocationText").GetComponent<Text>();
locationText.text = "Location";
if (!Permission.HasUserAuthorizedPermission(Permission.CoarseLocation))
{
Permission.RequestUserPermission(Permission.CoarseLocation);
}
}
void OnGUI()
{
if (!Permission.HasUserAuthorizedPermission(Permission.CoarseLocation))
{
// permission denied, no access should be visible, when activated when requested permission
locationText.text = "Permission denied";
return;
}
GetLastLocation();
}
public void GetLastLocation()
{
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(new Context());
try
{
Task lastLocation = null;
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HD_ACCURACY);
lastLocation = mFusedLocationProviderClient.getLastLocationWithAddress(mLocationRequest);
lastLocation.addOnSuccessListener(new HmsSuccessListener<Location>((location) =>
{
if (location == null)
{
locationText.text = "getLastLocation onSuccess location is null";
return;
}
locationText.text = "getLastLocation onSuccess location[Longitude,Latitude]:" + location.getLongitude() + "," + location.getLatitude();
})).addOnFailureListener(new HmsFailureListener((Exception e) =>
{
locationText.text = "getLastLocation onFailure " + e.toString();
}));
}
catch (System.Exception e)
{
locationText.text = "getLastLocation exception:" + e.Message;
}
}
public class HmsSuccessListener<T> : OnSuccessListener
{
public SuccessCallBack<T> CallBack;
public HmsSuccessListener(SuccessCallBack<T> c)
{
CallBack = c;
}
public void onSuccess(T arg0)
{
locationText.text = "OnSuccessListener onSuccess";
if (CallBack != null)
{
CallBack.Invoke(arg0);
}
}
public override void onSuccess(AndroidJavaObject arg0)
{
locationText.text = "OnSuccessListener onSuccess";
if (CallBack != null)
{
Type type = typeof(T);
IHmsBase ret = (IHmsBase)Activator.CreateInstance(type);
ret.obj = arg0;
CallBack.Invoke((T)ret);
}
}
}
public class HmsFailureListener : OnFailureListener
{
public FailureCallBack CallBack;
public HmsFailureListener(FailureCallBack c)
{
CallBack = c;
}
public override void onFailure(Exception arg0)
{
locationText.text = "OnFailureListener onFailure";
if (CallBack != null)
{
CallBack.Invoke(arg0);
}
}
}
}
Cree su archivo apk haciendo clic en Archivo> Configuración de compilación> Compilar e instalarlo en su dispositivo.
Abra su juego, acepte la solicitud de permisos de ubicación y vea el resultado.

Reference
이 문제에 관하여(Integrar Unity 및 위치 키트), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/huaweidevslatam/integrar-unity-location-kit-51pp텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)