Unity WebGL、js发布交互

Unity3D开发之unity和js通信交互 3.Unity3D开发之unity和js通信交互(老版方法)2.C#(挂在场景 任意物体上) 阅读详情

官网参考
Unity3D开发之WebGL平台上 unity和js前端通信交互

在这里插入图片描述
在这里插入图片描述

WebFun.jslib

mergeInto(LibraryManager.library, {

  JSLog: function (str) { 
	var strs=UTF8ToString(str); 
    
	Log(str); 
	Log(strs);
  }, 
  Hello: function () {
	var strs="Hello, world!"; 
	Log(strs); 
	Log(UTF8ToString(strs)); 
  }, 
  HelloString: function (str) { 
	Log(str); 
	Log(UTF8ToString(strs)); 
  }, 
  PrintFloatArray: function (array, size) { 
	var strs="";
	for(var i = 0; i < size; i++)
	{
		var data =   HEAPF32[(array >> 2) + i]; 
		strs+=data;
		if(i!=size-1)
		{
			strs+=",";
		}
	}  
	Log(strs); 
	Log(UTF8ToString(strs)); 
  }, 
  AddNumbers: function (x, y) { 
	var data = x + y; 
	Log(data); 
	Log(UTF8ToString(data)); 
    return data;
  }, 
  StringReturnValueFunction: function () {
    var returnStr = "bla";
    var bufferSize = lengthBytesUTF8(returnStr) + 1;
    var buffer = _malloc(bufferSize);
    stringToUTF8(returnStr, buffer, bufferSize); 
	Log(buffer);
	Log(UTF8ToString(buffer)); 
	return buffer;
  }, 
  BindWebGLTexture: function (texture) { 

    GLctx.bindTexture(GLctx.TEXTURE_2D, GL.textures[texture]);
	var strs="BindWebGLTexture";
	Log(strs);
	Log(UTF8ToString(strs)); 	
  }, 
});

unitywebdata.js


// 网页端 JavaScript

var  gameInstance 
 
function setgameInstance( gameIn)
{ 
	LogTip("setgameInstance 33 :");
	
    gameInstance = gameIn;
	 
    LogTip("setgameInstance 333 :"+(gameInstance==null||gameInstance==undefined));
}
 
function LogTip(str)
{
   // console.log(str); 
   window.alert(str);
}
 
function Log(str)
{  
  SendToUnity(str)
}

function SendToUnity(message) {
    //发送消息给unity 
	//第一个参数:挂在脚本的物体 
	//第二个参数:unity被调用的函数 
	//第三个参数:函数传入的参数
    gameInstance.SendMessage('Demo', 'JSCallUnity', message);
}

function SetFunPos(cname, cvalue, exdays) {   //exdays表示天数

	var d = new Date();
	d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
	var expires = "expires=" + d.toGMTString(); 
	document.cookie = cname + "=" + cvalue + "; " + expires;
	
	
	LogTip(`SetFunPos\r\ncname=${cname}:${cvalue};${exdays}\r\ncname=${cname}:${cvalue};${expires}` );
}

function GetFunPos (cname) {
	var returnArg;    //传出去的参数
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i].trim();
		if (c.indexOf(name) == 0) {
			returnArg = c.substring(name.length, c.length);
			LogTip(`GetFunPos\r\ncname=${cname}:${returnArg}` );
			//gameInstance.SendMessage("Test", "ReciveCookieMsg", returnArg);
			//发送消息给unity 
			//第一个参数:挂在脚本的物体 
			//第二个参数:unity被调用的函数 
			//第三个参数:函数传入的参数
			gameInstance.SendMessage('Demo', 'JSCallUnityRespone', returnArg);
			return; // returnArg;
		}
	}
	return "";
}
 
using UnityEngine;
using System.Runtime.InteropServices;
using UnityEngine.UI;

public class UnityWebCtrl : MonoBehaviour
{

    #region WebFun.jslib

    //This Log method is the one written by the front end
    // Several methods can be added here. Remember to separate the methods with commas.
    // Otherwise, an error will be reported when packaging on the WebGL platform
    //When packaging, there cannot be any Chinese characters in jslib. Annotations are not acceptable either. Otherwise, this error will be reported.
    //Building Library\Bee\artifacts\WebGL\build\debug_WebGL_wasm\build.js failed with output:
 
    [DllImport("__Internal")]
    private static extern void Hello();

    [DllImport("__Internal")]
    private static extern void HelloString(string str);

    [DllImport("__Internal")]
    private static extern void PrintFloatArray(float[] array, int size);

    [DllImport("__Internal")]
    private static extern int AddNumbers(int x, int y);

    [DllImport("__Internal")]
    private static extern string StringReturnValueFunction();

    [DllImport("__Internal")]
    private static extern void BindWebGLTexture(int texture);
 
    [DllImport("__Internal")]
    private static extern void JSLog(string str); //此处传入的类型和调用时候传入的数据类型一定要一致
     
    
    #endregion
    
    void Start()
    {
		AddText( "********************");
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.O))
        {
            UnityCallJs();
        }
        if (Input.GetKeyDown(KeyCode.P))
        { 
            UnityCallJs_old(); 
        }
        if (Input.GetKeyDown(KeyCode.K))
        {
            AddText($"***456asd123***");
        }
        
    }

    void UnityCallJs_old()
    { 
        int num = System.DateTime.Now.Second;
        AddText($"SetFunPos:{num}");
        Application.ExternalCall("SetFunPos", "PosX", num);
    
        AddText($"GetFunPos:{num}");
        Application.ExternalCall("GetFunPos", "PosX");
    }

    void UnityCallJs()
    { 
        AddText($"***456艾斯黛拉看123***");
        
        string msg = null;
        AddText($"Reqset  Hello:");
        Hello();
       

        msg = "This is a string.";
        AddText($"Reqset  HelloString:{msg}");
        HelloString(msg);
       

        float[] myArray = new float[10];
        AddText($"Reqset  PrintFloatArray:");
        PrintFloatArray(myArray, myArray.Length);
      
        
        AddText($"Reqset  AddNumbers:5,7");
        int result = AddNumbers(5, 7);
        AddText($"Respone  AddNumbers:{result}");

        
        AddText($"Reqset  StringReturnValueFunction:");
        msg = StringReturnValueFunction();
        AddText($"Respone  StringReturnValueFunction:{msg}");

        
        AddText($"Reqset  BindWebGLTexture:");
        var texture = new Texture2D(0, 0, TextureFormat.ARGB32, false);
        BindWebGLTexture(texture.GetNativeTextureID());
       

        AddText($"Reqset  JSLog:");
        JSLog("666");
    }
 
    public void JSCallUnity(string msg)//web js 回调
    {
        AddText($"JSCallUnity Receive:{msg}");
    }

    public  void JSCallUnityRespone(string str) //web js 回调
    {  
        AddText($"JSCallUnityRespone Receive:{str}");
    }

    [SerializeField] private Text text;

    private void AddText(string value)
    {
        if (text == null)
            return;
        text.text += $"[{System.DateTime.Now.ToString()}]:{value}\r\n"  ;
    }
}

index.html 补充

<script>
	var buildUrl = "Build";
	var loaderUrl = buildUrl + "/demoTests.loader.js";
	var config = {
		dataUrl: buildUrl + "/demoTests.data",
		frameworkUrl: buildUrl + "/demoTests.framework.js",
		codeUrl: buildUrl + "/demoTests.wasm",
		streamingAssetsUrl: "StreamingAssets",
		companyName: "DefaultCompanyTest",
		productName: "EnhanceScrollView",
		productVersion: "1.1",
		showBanner: unityShowBanner,
	};
 	var canvas = document.querySelector("#unity-canvas")
 	
	function loadScript(url, callback) { 
		var script = document.createElement("script"); 
		script.type = "text/javascript";  
		script.src = url; 
		script.onload = callback
		document.head.appendChild(script); 
    }; 
   
	createUnityInstance(canvas, config, (progress) => {
	
	}).then((unityInstance) => { 
		// window.alert("setgameInstance 00");
		loadScript("unitywebdata.js", (script2)=> {
			// window.alert("setgameInstance 11"); 
			// script2.setgameInstance(unityInstance);//Error
			var fun = setgameInstance; //引用abc函数
			fun(unityInstance); 
		}); 
	}); 
 </script>

IIS web.config

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <remove fileExtension=".mem" />
      <remove fileExtension=".data" />
      <remove fileExtension=".unity3d" />
      <remove fileExtension=".jsbr" />
      <remove fileExtension=".membr" />
      <remove fileExtension=".databr" />
      <remove fileExtension=".unity3dbr" />
      <remove fileExtension=".jsgz" />
      <remove fileExtension=".memgz" />
      <remove fileExtension=".datagz" />
      <remove fileExtension=".unity3dgz" />
      <remove fileExtension=".json" />
      <remove fileExtension=".unityweb" />
 
      <mimeMap fileExtension=".mem" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".data" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".unity3d" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".jsbr" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".membr" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".databr" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".unity3dbr" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".jsgz" mimeType="application/x-javascript; charset=UTF-8" />
      <mimeMap fileExtension=".memgz" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".datagz" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".unity3dgz" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".json" mimeType="application/json; charset=UTF-8" />
      <mimeMap fileExtension=".unityweb" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".ab" mimeType="application/octet-stream" />
	  <mimeMap fileExtension=".br" mimeType="application/octet-stream" />  
	  <!-- <mimeMap fileExtension=".wmv" mimeType="application/octet-stream" /> -->
    </staticContent>
        <directoryBrowse enabled="true" />
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Credentials: " value="true" />
                <add name="Access-Control-Allow-Headers" value="Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time" />
                <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
                <add name="Access-Control-Allow-Origin" value="*" />
            </customHeaders>
        </httpProtocol>
  </system.webServer>
</configuration>
Unity 与 JavaScript 的通信交互:实现跨平台的双向通信 在现代游戏开发和 Web 应用中,Unity 和 JavaScript 的结合越来越常见。Unity 是一个强大的跨平台游戏引擎,而 JavaScript 是 Web 开发的核心技术之一。通过 Unity 和 JavaScript 的通信交互,开发者可以实现从 Unity 到 Web 页面的功能扩展,或者从 Web 页面控制 Unity 的行为。这种双向通信的能力为开发者提供了更多的可能性,例如在 Unity 中嵌入 Web 视图,或者在 Web 页面中嵌入 Unity 游戏。 阅读详情

相关推荐

Unity 2021 发布WebGL之后, 实现和网页(JS)进行交互

Unity WebGL JS 交互

LWKlwk11的博客 2634

Unity发布webGL报错之无法生成build.js文件

Unity发布webGL报错之无法生成build.js文件

ttod的博客 4091

Unity+chatgpt+webgl实现声音录制+语音识别

AI二次元女友这个项目持续更新,在window端的语音识别和语音合成的功能,在上一篇博文里已经详细说明了微软Azure语音服务的代码实现。也是为了实现一次代码,多端复用这样的诉求,所以全部的代码实现都改成了web api的方式。然而在实测发布到webgl的时候,就发现了一个问题,因为这个项目涉及到麦克风录制声音,用作语音识别,结果在发布的时候,引擎报错,提示unity发布到webgl失败了,查了一下相关资料,原来是unity内置的microphone类是不支持webgl了,所以只好另找解决方案。

sinat_28962939的博客 4252

unity转小游戏报错Building Library\Bee\artifacts\WebGL\Building Library\Bee\artifacts\WebGL\build\debug_W

system_libs:WARNING: main() is in the input files, but "_main" is not in EXPORTED_FUNCTIONS, which means it may be eliminated as dead code. Export it if you want main() to run.

czh986911的博客 4195

i.MX RT1064引脚配置与BGA封装选型实战指南

在嵌入式硬件设计中,引脚配置与PCB布局是连接芯片手册与物理实现的关键桥梁,直接影响系统的稳定性与信号完整性。其核心原理在于理解处理器的IOMUX(输入/输出多路复用器)系统与多电源域架构,前者通过软件配置实现引脚功能的灵活复用,后者则为不同外设接口提供独立的电压基准,是保障电源稳定性的基石。从技术价值看,合理的引脚规划能规避信号干扰、电源不稳等潜在风险,提升设计一次成功率。在应用场景上,无论是连接SDRAM、USB、SDIO等高速外设,还是配置UART、I2C等中低速接口,都需要遵循特定的布局布线规则。本

weixin_33217202的博客 316

如何加载交易策略EA到MT4/MT5

1、打开MT4/MT5软件 2、首先,必须有一个EA,而且必须是mq4/ex4为扩展名。点击左上角“文件”—“打开数据文件夹”,找到安装路径 3、将EA的ex4或mq4文件放到MT4目录\MQL4\Experts里面(本文以名为Demo的EA为例) 4、如果有DLL库文件,复制到experts目录下的libraries子目录中 5、如果有tpl模板文件,复制到templates目录中 6、添加完成后重启MT4,点击允许EA运行图标 7、在导航中找到刚才安装的EA,拖拽到...

weixin_41364817的博客 7378

unity2d转微信小程序报错

Building Library\Bee\artifacts\WebGL\build\debug_WebGL_wasm\build.js failed with output:报错处理

weixin_45184581的博客 6709

ICG setup timing violation介绍?

门控时钟(clock gating)在RTL级电路设计过程中进行低功耗优化常用方法,能够有效降低动态功耗(翻转功耗)。Clock gating cell 可以由与门,与非门,或门或者或非门构成,但很容易产生Glitch。在实际使用中,一般用ICG(集成门控时钟单元)来完成clock gating。 下图展示了glitch的产生原因 在CTS时钟树综合的时候,ICG不会被看作sink,通常放置在source点附近,因此就会出现如上图这种结果。上图可以看出,在分析DFF到ICG的setup timing

m0_61003348的博客 9821

Unity-WebGL发布之C#与JS通信交互

版本:Unity2020.3.28 官方文档 最近项目要发布到WebGL,最近刚开始捣鼓。目前要实现Web端播放rtsp,看了很多文章都是在web端解决unity发布WebGL后如何播放rtsp。本人亲测了UMP2.0.3插件,可以在window下现实rtsp播放,但发布到Web端后会提示跨越错误,希望有大佬可以指点指点。 既然准备在web端解决unity发布WebGL后如何播放rtsp的问题,那么在发布WebGL后C#如何与JS通信交互呢? 直奔主题 1.在 Assets 文件夹中的“Plugi

NslCarry的博客 4419

STM32F407 BootLoader实战:从零搭建到OTA升级(附完整源码)

本文详细介绍了为STM32F407微控制器从零搭建BootLoader并实现稳定OTA升级的完整实战指南。内容涵盖Flash分区规划、链接脚本配置、核心跳转逻辑、中断向量表重定向、可靠的升级流程设计,并深入探讨了双备份与回滚机制以提升工业级可靠性。文章提供了可直接使用的代码框架,并分享了关键调试技巧,帮助开发者快速掌握STM32远程固件更新技术。

weixin_29192211的博客 458

树莓派5搭建ROS1开发环境:从系统安装到环境变量配置

本文详细指导如何在树莓派5上搭建ROS1开发环境。针对树莓派OS非标准安装路径导致的常见CMake报错问题,提供了从系统烧录、一键安装ROS到关键环境变量配置的完整解决方案,确保工作空间能成功编译,助力机器人项目开发。

weixin_29159127的博客 394

Unity发布WebGL使用JavaScript交互

本文介绍了Unity WebGL与HTML页面交互的方法。主要内容包括:1)通过jslib文件实现C#调用JavaScript方法,需要注意字符串转换;2)调用页面自带JavaScript函数的方法;3)修改HTML元素内容和样式的具体步骤。文章通过创建jslib插件、C#方法声明和调用示例,详细说明了如何实现Unity与HTML的双向通信,并提供了测试按钮来验证交互效果。特别强调了WebGL项目必须通过服务器访问,以及字符串参数需要UTF8ToString转换等注意事项。

阿赵的博客 1571

HITS算法详解及代码实现

占坑

蓁蓁尔的博客 7469

Unity 发布WebGL平台,C#与JavaScript交互

(JavaScript Library)是Unity的一种机制,允许你在C#中通过JavaScript代码来执行一些操作。这是一种高级的技巧,主要用于一些特殊情况,比如在WebGL项目中使用JavaScript来实现与Web页面的互操作。3.利用Assets/Plugins/WebGL/jslib桥接。发布H5平台,接入SDK,比如微信等,涉及到C#与JS的交互。2.javascript层实现逻辑。

yhhwatl的专栏 1347

Python 爬虫实战:豆瓣电影海报批量获取(Top250 榜单 + 可视化展示)

在信息爆炸的时代,数据已成为决策的核心,而数据的获取是数据分析的第一步。本文将详细介绍如何利用 Python 爬虫获取豆瓣电影 Top250 榜单的海报,并对数据进行可视化展示,助你更好地了解电影市场的趋势和用户的喜好。

yansideyucsdn的博客 723

手把手教你学 MATLAB 实战训练(6.9):卷积神经网络(CNN)模型来进行图像分类任务(预训练的 ResNet-50 模型)

加载数据集数据预处理加载预训练模型修改和扩展预训练模型设置训练选项训练模型测试模型。

xiaoheshang_123的博客 652

Unity 发布WebGL并与JS进行传参交互

    Unity发布WebGL后&lt;head&gt;标签中脚本内容为:var gameInstance = UnityLoader.instantiate("gameContainer", "Build/WebGlTest.json", { onProgress: UnityProgress });    在其后添加交互方法GetName:var gameInstance = UnityLo...

Loong的博客 1万+

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

unity webgl与 js 交互

unity webgl与 js 交互前言一、发布webgl 方式第一种方式:第二种方式:二、unity 与js 交互 架构定义js 方法c# : 调用JS 调用jsjs调用c#js 全局变量:总结 前言 最近发布到 webgl 平台还是有很多坑 需要注意 。 一、发布webgl 方式 第一种方式: 1,点击 unity buildsetting 页面 build and run 第二种方式: 搭建一个springboot 服务器 然后把 build出来的 三个文件 放在 访问: http://lo

ithinking110的博客 1934

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

探索未来Web交互:Unity与Vue的梦幻联动

在这个数字化的时代,身临其境的用户体验已经成为网页应用的关键。今天,我们将揭秘一款令人兴奋的开源项目——《Unity 打包成WebGL与Vue交互Demo》,这是一把解锁3D互动世界的钥匙,让Unity的强大游戏制作能力和Vue.js的灵动前端设计无缝对接。 ## 项目介绍 此项目为勇敢的开发者们搭建了一座桥梁,让Unity开发的精美3D内容能够流畅地游走在Web的海洋之中。通过将Unity项

gitblog_09765的博客 1270

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

WebGL调用JS对接小米H5sdk

一、 Unity:创建一个名为Show脚本挂载在Main Camera上 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Show : MonoBehaviour { public Text showTex...

9624 898

Unity发布webgl之后打开PDF文件,不使用js,不和浏览器交互

Unity发布webgl之后打开PDF文件

学不会shader 929

Unity发布WebGl注意事项

unity 版本是5.5,不过看了2017的文档好像也是差不多,绝大部分都是根据官方文档,希望有帮助,如果有错误或者你知道更多这方面的只是,请告知下,大恩言谢。 1:对webgl发布的工程文件说明 在release文件夹中,如果你使用了gzip压缩,那么你的文件后面会有个.gz 2:如何在pc上面运行webgl (1):发布webgl之后不能直接点(inde...

wangyihero8的专栏 1023

Unity | 发布WebGL遇到的那些事儿

发布WebGL后,遇到了跨域问题,原先可成功调用的上传、删除等接口报405错误 发布WebGL后,InputFeild输入框不支持复制粘贴 发布WebGL后,本地文件读取不了了

该用户还没想到好的昵称的博客 2218

关于Unity 中WebGL 与Http通信

1;什么是Unity webGLwebGL 的编译选项允许unity发布像使用了HTML5和webGL渲染API技术来使unity程序可以跑在浏览器中的javascript 程序。想要编译和测试WebGL程序,只需要在Build Playersetting里选择WebGL编译平台即可。 2:unity是怎么样发布为webGl程序的 为了运行webgl,需要我们的所有代码都是采用JavaScript...

lwsas1的专栏 7158

Unity webGL以及HTML与unity通信

转载至:http://blog.csdn.net/u010989951/article/details/70918067 1;什么是Unity webGL webGL 的编译选项允许unity发布像使用了HTML5和webGL渲染API技术来使unity程序可以跑在浏览器中的JavaScript 程序。想要编译和测试WebGL程序,只需要在Build Playersetting里选

暗黑者的博客 3745

JS传递值给Unity

1.unity发布成WebGL后,打开后缀为.html 在.html中添加以下内容 <script> var gameInstance = UnityLoader.instantiate("gameContainer", "Build/tt.json", {onProgress: UnityProgress}); </script> <script> function GetIDd(id) //注:函数名和unity中的保持一致 {...

qq_51992307的博客 673
上一篇: unity 镜面 反射
cwl72
博客等级 码龄9年 95粉丝 41原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值