当前位置:网站首页>Zero foundation uses unity3d to develop AR applications and download 3D models remotely
Zero foundation uses unity3d to develop AR applications and download 3D models remotely
2022-07-28 17:25:00 【mojocube】
Tools :Unity Version 2020.1.6f1c1 Personal、EasyAR 4.1
download :https://unity.cn/releases、https://www.easyar.cn/view/download.html#download-nav2
register :Unity Register individual developers to obtain licenses ,EasyAR Also register personal free edition .
open Unity, Create a new one Unity3D project , Double-click the downloaded EasyAR Plug in and import :
![]()

Sign in EasyAR Development Center , Create an app :


Open the project , hold Key Paste in :


Create a project : We use EasyAR This plugin , The official website has given a relatively perfect case , We can refer to :https://www.easyar.cn/view/download.html#download-nav2
preparation :

We right click on the blank space of the directory to add a C# Script, Put all the code in LoadAR.cs.




The export model ( Preforms ):


Write export code :
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
public class AssetBundleBuilder
{
[MenuItem("Assets/Build AssetBundle")]
static public void BuildAssetBundle()
{
Caching.ClearCache ();
string path = Application.streamingAssetsPath + "/" + "AssetBundles" + "/" + "Machine";
if (!Directory.Exists (path))
{
Directory.CreateDirectory(path);
}
BuildPipeline.BuildAssetBundles (path,0,EditorUserBuildSettings.activeBuildTarget);
AssetDatabase.Refresh ();
}
}

The generated file is in Assets\StreamingAssets\AssetBundles\Machine( The name depends on your )

If the server is IIS Of , You can add Web.config The code can be downloaded .a file , Otherwise 404 error :
<system.webServer>
<staticContent>
<mimeMap fileExtension=".a" mimeType="application/octet-stream" />
</staticContent>
</system.webServer>add controls :

To write LoadAR.cs Main code :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;
using UnityEngine.Networking;
using LitJson;
using System.Net;
using System.IO;
using System.Text;
using easyar;
public class LoadAR : MonoBehaviour
{
// Game FPS, It can be modified in the attribute window
public int targetFrameRate = 300;
//SessionID, This is used according to the specific business logic , It's not necessary
private string sessionId;
// Create a goal dynamically ( Recognizer )
private ImageTargetController imageTargetController;
// Create models dynamically
private GameObject myModel;
// When the program wakes up
void Awake()
{
// Modify the current FPS
//Application.targetFrameRate = targetFrameRate;
// Get remote server information
string url = "http://192.168.1.101/Default.aspx";
string data = "ClientKey=e10adc3949ba59abbe56e057f20f883e";
string result = HttpGet(url, data);
// analysis Json file
JsonData jdConfig = JsonMapper.ToObject(result);
sessionId = (string)jdConfig["sessionId"];
// obtain GUID And it is displayed in the upper left corner of the screen :
Text showGUID = GameObject.Find("Canvas").transform.GetChild(0).gameObject.GetComponent<Text>();
showGUID.text = "GUID: " + sessionId;
// Load the model dynamically and add it to ImageTarget below
//myModel = (GameObject)Instantiate(Resources.Load("Machine-Mask"));
//myModel.transform.parent = GameObject.Find("ImageTarget").transform;
// Change button text
Button submit = GameObject.Find("Canvas").transform.GetChild(2).gameObject.GetComponent<Button>();
Text btnSubmitTxt = submit.transform.GetChild(0).gameObject.GetComponent<Text>();
btnSubmitTxt.text = " change another one ";
// Add button event
submit.onClick.AddListener(ButtonClick);
imageTargetController = CreateTargetNode("ImageTarget-ID");// Dynamically create recognition objects
}
// The application starts executing
void Start()
{
}
// amount to Timer, Update every second
void Update()
{
ShowTime(DateTime.Now.ToString("HH:mm:ss"));
//LoadModel();
}
// Button event
void ButtonClick()
{
LoadModel();
}
// Show time text
private void ShowTime(string text)
{
Text showTime = GameObject.Find("Canvas").transform.GetChild(1).gameObject.GetComponent<Text>();
showTime.text = text;
}
private string loadUrl="";
private string loadName="";
// Get the download list remotely
private void LoadModel()
{
string url = "http://192.168.1.101/GetModel.aspx";
string data = "SessionID=" + sessionId;
string result = HttpGet(url, data);
try
{
JsonData jdModel = JsonMapper.ToObject(result);
if(loadUrl!=(string)jdModel["url"])
{
loadUrl=(string)jdModel["url"];
loadName=(string)jdModel["name"];
StartCoroutine(LoadAssets(loadUrl,loadName));
}
}
catch
{
}
}
// Download the model remotely and load it into ImageTarget Next
IEnumerator LoadAssets(string url,string name)
{
if(url!=null && url!="")
{
UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url);
yield return request.SendWebRequest();
AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);
GameObject go = ab.LoadAsset<GameObject>(name);
Destroy(myModel);// Destroy the previous model
// stay GameObject Add an object under the node , In order to be in target Show when tracked .
myModel = (GameObject)Instantiate(go);
myModel.transform.parent = imageTargetController.gameObject.transform;
}
}
// Dynamically create the component properties of the target
private ImageTargetController CreateTargetNode(string targetName)
{
GameObject go = new GameObject(targetName);
var targetController = go.AddComponent<ImageTargetController>();
ImageTrackerFrameFilter imageTracker = FindObjectOfType<ImageTrackerFrameFilter>(); // Get trace events
imageTracker.enabled = true;
targetController.Tracker = imageTracker;
targetController.SourceType = ImageTargetController.DataSource.ImageFile;
targetController.ImageFileSource.PathType = PathType.StreamingAssets;
targetController.ImageFileSource.Path = "idcard.jpg"; // Identify pictures
targetController.ImageFileSource.Name = "ID Card";
targetController.ImageFileSource.Scale = 10;
return targetController;
}
//GET Request and obtain results
public static string HttpGet(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
}
Configure Android build environment , Generate APK file :






Generate APK Under the project root :

Send it to Android mobile phone to install and run AR application :

Click on another button , You can download and display another model :

边栏推荐
- Function接口之andThen
- Application of Pegasus d200s UAV and airborne lidar in large-scale DEM construction
- Selection and application of inductors in high speed circuits
- 高速电路中电阻的选择
- Verilog daily question (vl5 signal generator)
- wpf命令按钮透明样式
- The practice of beego framework in goweb development: Section I Introduction to beego framework
- Goweb开发之Beego框架实战:第三节 程序执行流程分析
- 【ansible】ansible shell 执行远程命令遇到awk 中$符号的问题
- Analysis of kubernetes service principle
猜你喜欢

The practice of beego framework in goweb development: Section I Introduction to beego framework

Unity shader procedural texture

Why do I choose to use go language?

Verilog daily question (simple implementation of VL30 RAM)

Goweb开发之Beego框架实战:第三节 程序执行流程分析

Goweb开发之Beego框架实战:第四节 数据库配置及连接

The practice of beego framework developed by goweb: Section 4 database configuration and connection

kubernetes service 原理解析

Fine-grained Fact Verification with Kernel GA Network

利用SQL Server代理作业对数据库进行定时还原
随机推荐
The practice of the beego framework for goweb development: Section V project construction and user registration
Iris framework practice of goweb development: project summary and review
格雷码和二进制的转换及典型例题(4bits格雷码计数器)
Vscode界面介绍
Some attention code explanations
Several methods of importing excel file data by C #
2021年4月份自考
批量下载文件
高速电路中电感的选型和应用
2022牛客多校第二场CDE
Net framework
Unity shader depth of field effect
Unity3d simple implementation of water surface shader
微服务架构-服务注册中心和服务网关(6.8) (转载)
C#遍历集合
C# 导入Excel文件数据的几种方法
一文了解 Kubernetes 中的服务发现
Function接口之andThen
【presto】presto 常用的命令
Azure Devops developed by visual studio 2015 team