Unity3D脚本中文教程
Unity3D一些比较基本的脚本及组件(C#)
Unity3D⼀些⽐较基本的脚本及组件(C#)通过代码创造图形//创建顶点,创建序列,创建⽹格,然后把⽹格赋给⽹格序列器//draw a trianglevoid Start () {Vector3[] vs = new Vector3[3];vs[0] = new Vector3(0,0,0);vs[1] = new Vector3(1,0,0);vs[2] = new Vector3(0,1,0);int[ts] = new int[3];ts[0] = 0;ts[1] = 1;ts[2] = 2; //要注意顺序,要⽤左⼿系,法线向外,拇指向外Mesh mesh = new Mesh();GetComponet<MeshFilter>().mesh = mesh;mesh.vertices = vs; // vertices⾄⾼点mesh.triangles = ts;}///* */////draw a triangle程序封装代码public GameObject Create Triangle(){GameObject obj = new GameObject(“Triangle”);MeshFilter mf = obj.AddComponet<MeshFilter>();obj.AddComponent<MeshRender>();Mesh mesh = new Mesh();mesh.vertices = nes[]{new Vector3(0,0,0);new Vector3(3,0,0);new Vector3(0,3,0);};mesh.triangles = new[]{0,2,1//不⽤分号,初始化系,直接把初始值放进去};mf.mesh = mesh;return obj;}Camera 的性质与使⽤public CameraClearFlags clearFlags; //clearFlags是相机清除表识public ColorbackgroundColor; //给定他的颜⾊,背景⾊,只有单⾊才起作⽤public int cullingMask; //提出掩码public class chapter6 : MonoBehaviour{public GameObject cube;void Start(){ber = 9; //把cube设置在第9层Camera cam = this.GetComponet<Camera>()’cam.clearFlags = CameraClearFlags.SolidColor;cam.backgroundColor = new Vector3(1,0,0,0); //表⽰设置颜⾊cam.cullingMask = 9; //表⽰第9层的都不会被渲染出来,也就是说cube不会显⽰出来}}//CameraClearFlags是⼀个枚举类型,有以下四个成员:solidColor 表⽰⽤backgroundColor所制定的填充背景skybox 表⽰天空盒,模拟天空效果填充Depth 只是清除深度缓存,保留上⼀帧所使⽤的颜⾊Nothing 不进⾏背景清除,这种情况在游戏和模拟应⽤中⽐较少⽤public bool orthographic;//⽤于读取和设定相机的投影⽅式,如果为true则表⽰是正交投影,否则为透视投影;正交投影可⽤于UI和2D开发public float orthographicSize; //⽤以指定正交投影的视景体的垂直⽅向尺⼨的⼀半public Rect rect; //相机对应的视⾓⼝的位置和⼤⼩,rect以单位化形式制定相机视⼝在屏幕中的位置和⼤⼩,位置⼤⼩取值范围为0~1,满屏为1Camera main = this.gameObject.GetComponet<Camera>();this.gameObject.SetActive(false);Camera cam0 = camGO0.AddComponet<Camera>();cam0.orthographic = true;cam0.transform.position = main.transform.position;cam0.transform.rotation = main.transform. rotation;cam0.orthographicSize = 2.0f; //指物体渲染后显⽰的⼤⼩远近,数值越⼤,相机视⼝越靠近该物体,从⽽该物体显⽰出来的更加⼤cam0.rect = new Rect(0f,0f, 0.5f, 0.5f); //前两个参数是camera的位置,后⾯两个参数设置相机⼤⼩(0.5f,0.5f)表⽰占x轴的⼆分之⼀,y轴的⼆分之⼀,所以总共占渲染窗⼝的四分之⼀Camera cam1 = camGO1.AddComponet<Camera>();cam1.orthographic = true;cam1.transform.position = main.transform.position;cam1.transform.rotation = main.transform. rotation;cam1.orthographicSize = 7.0f;cam1.rect = new Rect(0.5f, 0.5f, 0.5f, 0.5f);}Material,Shader,Texture(材质,着⾊器,纹理)光照、纹理等让物体更加的真实。
(2020年整理)Unity3D常用脚本.pptx
if(screenbutton==true) if(GUI.Button(Rect(Screen.width/2-380,Screen.height/2-190,60,50),"Scene1")){
print("You click Scene1"); Application.LoadLevel (1); screenbutton = false; }else if(GUI.Button(Rect(Screen.width/2-380,Screen.height/2-130,60,50),"Scene2")){ print("You click Scene2"); Application.LoadLevel (2); screenbutton = false; }else if( GUI.Button(Rect(Screen.width/2-375,Screen.height/2-0,50,50),"Quit")){ print("You click Quit"); Application.Quit(); } } 心得: 场景转换时,这个程序贴在按钮界面场景中。在 Build Setting(导出)(在 File 下)菜单中加 入所需场景。
var particle : GameObject;
function Start(){ DontDestroyOnLoad(this); screnbutton=true;
word = Text; Text = ""; yield WaitForSeconds (2); TypeText ();
Unity3D教程:基础入门中文版
一、Unity基础本部分是你开始Unity的关键。
这里将解释Unity的界面,菜单项,使用资源,创建场景,和发布。
当你完全阅读了该部分后,你将能够理解Unity是如何工作的,以及如何使其更加有效的工作,和如何将简单的游戏放置在一起。
1.(Learning the interface)现在我们开始学习Unity,如果你还没有打开Unity,你可以通过双击位于Application->Unity文件夹中的Unity图标来运行它,当它第一次运行时你将看到如下的场景:Unity运时场,过实,图有很多需要学习的东西,让我们花费点时间来观察理解上述界面。
我们将介绍每一个接口元素。
概要主窗口的每一个部分都被称为视图(View)。
在Unity中有多种类型的视图,但是,你不需要同时看见所有的视图。
不同的布局模式(Layout modes)包含的视图是不同的。
通过单击布局下拉控件来选择不同的布局,该控件位于窗口的右上角。
选择现在,单击布局选择,并单击Animation,切换到动画布局(Animation layout)。
还可以从菜单中选择Window->Layouts->Animation来切换。
动画布局包含所有的视图,这是昀好的用来介绍它们的方法。
通过视图左上角的名称你可以迅速的分辨这些视图。
这些视图是:场景视图(Scene View)-用于放置物体游戏视图(Game View)-表示游戏在运行时的外观层次视图(Hierarchy)-当前场景中的游戏物体的列表工程视图(Project)-显示当前打开工程中所有可用的物体和资源检视视图(Instpector)-显示当前选中物体的细节和属性时间线(Timeline)-用于为当前选中物体创建基本的时间线动画场景视图(Scene View)场视图场景视图(Scene View)是一个可交互的沙盘。
你将使用它来选择并在场景中定位所有的游戏物体(GameObjects),包括玩家,摄像机,敌人等。
Unity 3d英文翻译
Unity Manual 用户手册•用户指南o Unity基础翻译:U_鹰▪学习界面翻译:U_鹰▪项目浏览器视图翻译:U_鹰▪层级面板视图翻译:U_鹰▪工具栏翻译:U_鹰▪场景视图翻译:U_鹰▪游戏视图翻译:U_鹰▪检视面板翻译:U_鹰▪其他视图翻译:U_鹰▪自定义工作区翻译:第七把剑▪资源工作流程翻译:第七把剑▪创建场景翻译:第七把剑▪编译发布翻译:第七把剑▪教程翻译:U_鹰▪Unity3D快捷键翻译:U_鹰▪首选项翻译:U_鹰o构建场景▪游戏对象翻译:第七把剑▪游戏对象和组件的关系翻译:第七把剑▪使用组件翻译:第七把剑▪组件和脚本之间的关系翻译:第七把剑▪停用游戏对象翻译:feicheng2005▪使用检视面板翻译:第七把剑▪编辑值属性翻译:第七把剑▪预设库翻译:U_鹰▪指定引用翻译:第七把剑▪多重对象编辑翻译:colin3dmax▪检视面板选项翻译:第七把剑▪使用场景视图翻译:第七把剑▪场景视图导航翻译:第七把剑▪定位游戏对象翻译:第七把剑▪视图模式翻译:第七把剑▪Gizmo和图标显示控制翻译:U_鹰▪搜索翻译:第七把剑▪预制翻译:第七把剑▪灯光翻译:第七把剑▪摄像机翻译:第七把剑▪地形引擎指南翻译:第七把剑o资源导入与创建翻译:第七把剑▪基本对象翻译:U_鹰▪导入资源翻译:第七把剑▪模型翻译:用生命舞蹈▪3D格式翻译:用生命舞蹈▪材质与着色器翻译:第七把剑▪二维纹理翻译:第七把剑▪程序材质翻译:U_鹰▪影片纹理翻译:U_鹰▪音频文件翻译:U_鹰▪音轨模块翻译:U_鹰▪使用脚本翻译:colin3dmax▪▪▪事件函数翻译:RICO▪▪▪▪▪资源商店翻译:肥耀▪▪资源商店发布者管理翻译:13y32r▪▪资源服务器(仅团队许可)翻译:colin3dmax▪设置资源服务器(仅团队许可)翻译:青青子矜▪缓存服务器(仅团队许可)▪缓存服务器(仅团队许可)翻译:一米的馒头▪缓存服务器常见问题翻译:13y32r▪场景幕后翻译:colin3dmaxo创建游戏翻译:U_鹰▪运行时实例化预置翻译:U_鹰▪输入翻译:U_鹰▪变换翻译:U_鹰▪物理翻译:U_鹰▪添加随机的游戏元素翻译:一米的馒头▪粒子系统翻译:小yue▪粒子系统曲线编辑器翻译:小yue▪粒子系统中的颜色和渐变翻译:小yue▪渐变编辑器翻译:小yue▪粒子系统检视面板翻译:小yue▪粒子系统模块介绍翻译:小yue▪粒子系统模块翻译:小yue▪粒子效果翻译:小yue▪Mecanim动画系统翻译:FancyBit▪动画和Mecanim术语表翻译:FancyBit▪资源准备和导入翻译:FancyBit▪准备你自己的角色翻译:FancyBit▪导入动画翻译:FancyBit▪分割动画翻译:FancyBit▪▪创建Avatar翻译:FancyBit▪配置Avatar翻译:FancyBit▪肌肉设定翻译:FancyBit▪阿凡达身体遮罩翻译:Karsion▪为类人动画重新定位目标翻译:Karsion▪▪Mecanim中的通用动画翻译:bwhale▪为角色赋予生命翻译:bwhale▪循环动画剪辑翻译:bwhale▪动画组件和动画控制器翻译:bwhale▪动画状态机翻译:bwhale▪动画状态翻译:bwhale▪动画状态转移翻译:bwhale▪动画参数翻译:bwhale▪混合树翻译:bwhale▪一维混合翻译:bwhale▪二维混合翻译:bwhale▪附加混合树选项翻译:bwhale▪Mecanim进阶主题翻译:bwhale▪使用Mecanim的动画曲线(仅限Pro版本)翻译:bwhale▪子状态机翻译:bwhale▪动画层翻译:bwhale▪动画状态机预览(独立和关闭)翻译:bwhale▪目标匹配翻译:bwhale▪根动作-如何工作翻译:bwhale▪教程:为一个人形场景动画编写根动作脚本翻译:bwhale▪Mecanim性能和优化翻译:feicheng2005▪Mecanim问答翻译:feicheng2005▪旧版动画系统翻译:feicheng2005▪动画视图指南翻译:U_鹰▪动画脚本翻译:U_鹰▪导航网格和寻路(仅专业版)翻译:肥耀▪导航网格烘焙翻译:肥耀▪声音翻译:U_鹰▪游戏界面元素翻译:U_鹰▪多人网络翻译:U_鹰Android•Android 开发入门翻译:闲人若林o安装Android SDK翻译:闲人若林o安卓远程工具翻译:闲人若林o故障排除翻译:U_鹰o在Android中报告崩溃BUG翻译:Summer Windso目前在Unity Android 中不支持的特性翻译:Summer Windso对分割应用程序二进制(.OBB)的支持翻译:悄悄o播放器设置翻译:U_鹰o Android脚本翻译:U_鹰▪输入翻译:U_鹰▪手机键盘翻译:雨天▪高级Unity手机脚本翻译:Summer Winds▪使用.NET API 兼容级别翻译:U_鹰o为Android创建插件翻译:雨天o自定义手机启动画面翻译:闲人若林Blackberry 10•ooooooWindows Store•oooooo▪o▪oWindows Phone 8•Windows Phone 8:入门翻译:Cantilenao Windows Phone 8:部署翻译:Cantilenao Windows Phone 8:调试翻译:Cantilenaooo▪▪o Windows Phone 8:常见问题翻译:Cantilenao▪•本地客户端开发入门翻译:peiandsky•Flash开发入门翻译:我是头觅食的野猪o Flash:安装翻译:我是头觅食的野猪o Flash:生成并运行翻译:我是头觅食的野猪o Flash:进行调试翻译:我是头觅食的野猪o Flash:支持和不支持的翻译:我是头觅食的野猪oooooo•常见问题o升级指南翻译:青青子矜o升级指南翻译:U_鹰o升级项目从到翻译:U_鹰▪物理升级细节翻译:U_鹰▪Mono升级细节翻译:U_鹰▪渲染升级细节翻译:U_鹰▪Unity 着色器转换指南翻译:U_鹰o Unity 激活- 概述翻译:U_鹰▪管理你的Unity 许可证翻译:U_鹰▪在线激活Unity 逐步指南翻译:U_鹰▪手工激活逐步指南翻译:U_鹰o游戏代码问题翻译:U_鹰▪如何制作一个简单的第一人称步骤?翻译:U_鹰o图形问题翻译:U_鹰▪如何导入Alpha纹理?翻译:我是头觅食的野猪▪如何使用法线贴图?翻译:我是头觅食的野猪▪如何使用细节纹理?翻译:杨希羚▪如何制作一个Cubemap纹理?翻译:杨希羚▪如何制作天空盒?翻译:我是头觅食的野猪▪如何制作网格粒子发射器?(旧的粒子系统)翻译:我是头觅食的野猪▪如何制作启动屏幕?翻译:杨希羚▪如何制作聚光灯投影遮罩?翻译:杨希羚▪如何修正导入模型的旋转?翻译:我是头觅食的野猪▪如何使用水?翻译:杨希羚o如何导出FBX翻译:我是头觅食的野猪o怎样高效部署资源文件实践指南翻译:一米的馒头o如何从3d应用程序中导入物体?翻译:用生命舞蹈▪从maya导入物体翻译:用生命舞蹈▪从Cinema 4D导入物体翻译:用生命舞蹈▪从3D Studio Max导入物体翻译:用生命舞蹈▪从Cheetah3D导入物体翻译:我是头觅食的野猪▪从Modo导入物体翻译:我是头觅食的野猪▪从Lightwave导入物体翻译:我是头觅食的野猪▪从Blender导入物体翻译:我是头觅食的野猪▪o工作流程问题▪(Mono Develop入门)翻译:肥耀▪怎样在项目间重用资源?翻译:肥耀▪怎样安装和升级标准资源包?翻译:肥耀▪平台间的项目移植翻译:Cantilenao移动开发者清单翻译:悄悄▪系统崩溃翻译:悄悄▪性能分析翻译:悄悄▪优化翻译:悄悄o•高级o向量介绍翻译:冷水泡面▪理解向量运算翻译:冷水泡面▪从一个对象到另一个对象的方向和距离翻译:冷水泡面▪计算法线向量/垂直向量翻译:冷水泡面▪一个向量的大小的数量位于另一个向量方向上翻译:冷水泡面o资源包(仅专业版)翻译:bwhale▪资源包问答翻译:bwhale▪创建资源包翻译:bwhale▪下载资源包翻译:bwhale▪从资源包中加载资源翻译:bwhale▪追踪所下载的资源包翻译:bwhale▪存储加载资源包中的二进制数据翻译:bwhale▪内容保护翻译:bwhale▪管理资源依赖关系翻译:bwhale▪在资源包中包含脚本翻译:bwhaleo图形功能▪高动态范围(HDR)图像翻译:肥耀▪渲染路径翻译:肥耀▪线性光照(仅专业版)翻译:U_鹰▪细节级别(仅专业版)翻译:肥耀▪着色器翻译:肥耀▪着色器:着色器语言&固定功能着色器翻译:风里疯语▪着色器:顶点和片段程序翻译:风里疯语▪在Unity 4使用DirectX 11翻译:U_鹰▪计算着色器翻译:13y32r▪图形仿真翻译:我是头觅食的野猪o资源数据库翻译:肥耀o构建播放器管线翻译:我是头觅食的野猪o分析器(仅专业版)翻译:肥耀▪分析器窗口翻译:肥耀▪CPU使用率区域翻译:Cantilena▪渲染区域翻译:肥耀▪内存区域翻译:Cantilena▪音频区域翻译:Cantilena▪物理学区域翻译:肥耀▪GPU区域翻译:肥耀o光照贴图快速入门翻译:用生命舞蹈▪光照贴图深入学习翻译:用生命舞蹈▪自定义Beast设置翻译:一米的馒头▪光照贴图UV翻译:用生命舞蹈▪灯光探测器翻译:用生命舞蹈o遮挡剔除(仅专业版)翻译:肥耀o摄像机技巧翻译:U_鹰▪了解视锥体翻译:重生の记忆▪从摄像机到给定距离的视锥体的大小翻译:我是头觅食的野猪▪推拉变焦(又称伸缩变焦)翻译:我是头觅食的野猪▪摄像机射线翻译:我是头觅食的野猪▪使用斜视锥体翻译:我是头觅食的野猪▪创建一个大或小尺寸的感觉翻译:我是头觅食的野猪o在运行时加载资源翻译:肥耀o通过脚本修改源资源翻译:肥耀o用程序生成网格几何体翻译:肥耀▪网格剖析翻译:肥耀▪使用Mesh类翻译:肥耀▪示例- 创建一个广告牌平面翻译:肥耀o富文本翻译:无悔o在Unity项目中使用Mono DLL(动态链接库)翻译:X-droido事件函数的执行顺序翻译:X-droido优化手机的实用指南翻译:Cantilena▪优化手机的实用指南- 未来及高端设备翻译:Cantilena▪优化手机的实用指南- 图形方法翻译:Cantilena▪优化手机的实用指南- 脚本和游戏设置方法翻译:萤之助▪优化手机的实用指南- 渲染优化翻译:萤之助▪o Unity XCode项目结构翻译:U_鹰o优化图形性能翻译:肥耀▪描绘调用批处理翻译:Amazonzx▪为优化性能建模角色翻译:肥耀▪渲染数据统计窗口翻译:肥耀o减小文件大小翻译:我是头觅食的野猪o了解自动内存管理翻译:一米的馒头o平台依赖编译翻译:我是头觅食的野猪o泛型函数翻译:肥耀o进行调试翻译:我是头觅食的野猪▪控制台翻译:U_鹰▪调试器翻译:我是头觅食的野猪▪日志文件翻译:肥耀▪访问隐藏文件夹翻译:肥耀o插件- 只用于专业版/移动版功能翻译:太昊|仙境乐网▪为桌面平台创建插件翻译:雨天▪为iOS创建插件翻译:雨天▪为Android创建插件翻译:雨天▪底层本地插件接口翻译:雨天o文本场景文件格式(仅专业版功能)翻译:U_鹰▪格式说明翻译:我是头觅食的野猪▪YAML场景示例翻译:我是头觅食的野猪▪YAML 类ID参考翻译:U_鹰o流媒体资源翻译:我是头觅食的野猪o命令行参数翻译:一米的馒头o启动时运行编辑器脚本代码翻译:U_鹰o网络仿真翻译:肥耀o网络播放器的安全沙箱翻译:我是头觅食的野猪o可用的.NET类库概述o Visual Studio C#集成翻译:我是头觅食的野猪oo使用Unity的外部版本控制系统翻译:我是头觅食的野猪o分析翻译:肥耀o更新检查翻译:肥耀o安装多个Unity版本翻译:青青子矜o故障排除翻译:U_鹰▪编辑器故障排除翻译:IanZhang▪网页播放器故障排除翻译:IanZhangDesktop•阴影翻译:U_鹰o平行光阴影细节翻译:U_鹰o阴影疑难解答翻译:U_鹰o阴影大小计算翻译:U_鹰o Unity的输入法编辑器翻译:U_鹰o为集成显卡优化翻译:U_鹰•网络播放器部署翻译:U_鹰o用HTML代码加载Unity内容翻译:U_鹰o使用精缩的UnityObject2翻译:IanZhango自定义Unity网络播放器加载的屏幕翻译:U_鹰o自定义Unity网络播放器的行为翻译:U_鹰o Unity网络播放器和浏览器通信翻译:U_鹰o使用网络播放器模板翻译:U_鹰o网络播放器流处理翻译:U_鹰o网页播放器版本翻译:人中吕布•在网页播放器使用信任链系统翻译:人中吕布。
unity3d MonoBehaviour章节中文翻译
MonoBehaviourInherits from Behaviour继承自BehaviourMonoBehaviour is the base class every script derives from.MonoBehaviour是每个脚本的基类.Using Javascript every script automatically derives from MonoBehaviour. When using C# or Boo you have to explicitly derive from MonoBehaviour.每个Javascript脚本自动继承MonoBehaviour.使用C#或Boo时,需要显式继承MonoBehaviour.Note: The checkbox for disabling a MonoBehavior (on the editor) will only prevent Start(), Awake(), Update(), FixedUpdate(), and OnGUI() from executing. If none of these functions are present, the checkbox is not displayed.注意:MonoBehavior对象(编辑器中)的复选框,只有在其有Start(), Awake(), Update(), FixedUpdate(), 和OnGUI()函数时显示,没有这些函数时则隐藏.(另注:译者在PC上Windows平台测试结果与此注释所描述情况不符)See Also: The chapter on scripting in the manual.VariablesuseGUILayout Disabling this lets you skip the GUI layout phase.禁用此项,将会跳过GUILayout部署Functions 函数Invoke Invokes the method methodName in time seconds.根据时间调用指定方法名的方法InvokeRepeating Invokes the method methodName in time seconds.根据时间调用指定方法名的方法CancelInvoke Cancels all Invoke calls on this MonoBehaviour.取消这个MonoBehaviour上的所有调用.IsInvoking Is any invoke on methodName pending?某指定函数是否在等候调用StartCoroutine Starts a coroutine.开始协同程序.StopCoroutine Stops all coroutines named methodName running on this behaviour.停止这个动作中名为methodName的所有协同程序.StopAllCoroutines Stops all coroutines running on this behaviour.停止所有动作的协同程序.Overridable Functions 可重载的函数Update Update is called every frame, if the MonoBehaviour is enabled.当MonoBehaviour启用时,其Update在每一帧被调用LateUpdate LateUpdate is called every frame, if the Behaviour is enabled.当MonoBehaviour启用时,其LateUpdate在每一帧被调用FixedUpdate This function is called every fixed framerate frame, if the MonoBehaviour is enabled.当MonoBehaviour启用时,其FixedUpdate在每一帧被调用Awake Awake is called when the script instance is being loaded.当一个脚本实例被载入时Awake被调用.Start Start is called just before any of the Update methods is called the first time.Start在Update调用前被调用.Reset Reset to default values.重置,恢复到默认值.OnMouseEnter OnMouseEnter is called when the mouse entered the GUIElement or Collider.当鼠标进入到GUIElement(GUI组件)或Collider(碰撞体)中时调用OnMouseEnter.OnMouseOver OnMouseOver is called every frame while the mouse is over the GUIElement or Collider.当鼠标悬浮在GUIElement(GUI组件)或Collider(碰撞体)上时调用OnMouseOver.OnMouseExit OnMouseExit is called when the mouse is not any longer over the GUIElement or Collider.当鼠标移出GUIElement(GUI组件)或Collider(碰撞体)上时调用OnMouseExitOnMouseDown OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collid当用户在GUIElement(GUI组件)或Collider(碰撞体)上点击鼠标时调用OnMouseDownOnMouseUp OnMouseUp is called when the user has released the mouse button.用户释放鼠标键的时候调用这个.OnMouseDrag OnMouseDrag is called when the user has clicked on a GUIElement or Collider and is still holding down thmouse.当用户鼠标拖拽GUIElement(GUI组件)或Collider(碰撞体)时调用OnMouseDragOnTriggerEnter OnTriggerEnter is called when the Collider other enters the trigger.当Collider(碰撞体)进入trigger(触发器)时调用OnTriggerEnter.OnTriggerExit OnTriggerExit is called when the Collider other has stopped touching the trigger.当Collider(碰撞体)移出trigger(触发器)时调用OnTriggerExit.OnTriggerStay OnTriggerStay is called once per frame for every Collider other that is touching the trigger.当Collider(碰撞体)触发trigger(触发器)时在每一帧调用OnTriggerStay.OnCollisionEnter OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider.当此collider/rigidbody触发另一个rigidbody/collider时,OnCollisionEnter将被调用.OnCollisionExit OnCollisionExit is called when this collider/rigidbody has stopped touching another rigidbody/collider.当此collider/rigidbody停止触发另一个rigidbody/collider时,OnCollisionExit将被调用. OnCollisionStay OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider.当此collider/rigidbody触发另一个rigidbody/collider时,OnCollisionStay将会在每一帧被调用. OnControllerColliderHit OnControllerColliderHit is called when the controller hits a collider while performing a Move.当controller碰撞到collider时OnControllerHit被调用.OnJointBreak Called when a joint attached to the same game object broke.当附在同一对象上的关节被断开时调用.OnParticleCollision OnParticleCollision is called when a particle hits a collider.当粒子碰到collider时被调用.OnBecameVisible OnBecameVisible is called when the renderer became visible by any camera.当renderer(渲染器)在任何相机上可见时调用OnBecameVisible.OnBecameInvisible OnBecameInvisible is called when the renderer is no longer visible by any camera.当renderer(渲染器)在任何相机上都不可见时调用OnBecameInvisible.OnLevelWasLoaded This function is called after a new level was loaded.当一个新关卡被载入时此函数被调用.OnEnable This function is called when the object becomes enabled and active.当对象变为可用或激活状态时此函数被调用.OnDisable This function is called when the behaviour becomes disabled () or inactive.当对象变为不可用或非激活状态时此函数被调用.OnPreCull OnPreCull is called before a camera culls the scene.在相机剪裁场景之前被调用.OnPreRender OnPreRender is called before a camera starts rendering the scene.在相机渲染场景之前被调用.OnPostRender OnPostRender is called after a camera finished rendering the scene.在相机完成场景渲染之后被调用.OnRenderObject OnRenderObject is called after camera has rendered the scene.在相机场景渲染完成后被调用OnWillRenderObject OnWillRenderObject is called once for each camera if the object is visible.如果对象可见每个相机都会调用它.OnGUI OnGUI is called for rendering and handling GUI events.渲染和处理GUI事件时调用.OnRenderImage OnRenderImage is called after all rendering is complete to render image当完成所有渲染后被调用,用来渲染图片后期效果.OnDrawGizmosSelected Implement this OnDrawGizmosSelected if you want to draw gizmos only if the object is selected.如果你想在物体被选中时绘制gizmos,去实现这个函数.OnDrawGizmos Implement this OnDrawGizmos if you want to draw gizmos that are also pickable and always drawn.如果你想绘制可被点选的gizmos,去实现这个.OnApplicationPause Sent to all game objects when the player pauses.当玩家暂停时发送到所有的游戏物体.OnApplicationFocus Sent to all game objects when the player gets or looses focus.当玩家获取或失去焦点时发送给所有游戏物体.OnApplicationQuit Sent to all game objects before the application is quit.在应用退出之前发送给所有的游戏物体.OnPlayerConnected Called on the server whenever a new player has successfully connected.当一个新玩家成功连接时在服务器上被调用.OnServerInitialized Called on the server whenever a Network.InitializeServer was invoked and has completed.当Network.InitializeServer被调用并完成时,在服务器上调用这个函数OnConnectedToServer Called on the client when you have successfully connected to a server当你成功连接到服务器时,在客户端被调用.OnPlayerDisconnected Called on the server whenever a player disconnected from the server.当一个玩家从服务器上断开时在服务器端调用.OnDisconnectedFromServer Called on the client when the connection was lost or you disconnected from the server.当失去连接或从服务器端断开时在客户端调用.OnFailedToConnect Called on the client when a connection attempt fails for some reason.当一个连接因为某些原因失败时在客户端调用.OnFailedToConnectToMasterServer Called on clients or servers when there is a problem connecting to the MasterServer.当连接主服务器出现问题时在客户端或服务器端调用.OnMasterServerEvent Called on clients or servers when reporting events from the MasterServer.当报告事件来自主服务器时在客户端或服务器端调用.OnNetworkInstantiate Called on objects which have been network instantiated with Network.Instantiate当一个物体使用Network.Instantiate进行网络初始化时调用. OnSerializeNetworkView Used to customize synchronization of variables in a script watched by a network view.在一个网络视图脚本中,用于自定义变量同步Class Functions 类函数print Logs message to the Unity Console. This function is identical to Debug.Log.记录消息到Unity控制台.这个函数和Debug.Log作用相同.Inherited members 被继承的成员Inherited Variables 被继承的变量enabled Enabled Behaviours are Updated, disabled Behaviours are not.启用时Behaviours会执行更新,反之不更新.transform The Transform attached to this GameObject (null if there is none attached).附加在本游戏对象上的Transform(没有则为null).rigidbody The Rigidbody attached to this GameObject (null if there is none attached).附加在本游戏对象上的Rigidbody(没有则为null).camera The Camera attached to this GameObject (null if there is none attached).附加在本游戏对象上的Camera(没有则为null).light The Light attached to this GameObject (null if there is none attached).附加在本游戏对象上的Light (没有则为null).animation The Animation attached to this GameObject (null if there is none attached).附加在本游戏对象上的animation (没有则为null).constantForce The ConstantForce attached to this GameObject (null if there is none attached).附加在本游戏对象上的ConstantForce(没有则为null).renderer The Renderer attached to this GameObject (null if there is none attached).附加在本游戏对象上的Renderer(没有则为null).audio The AudioSource attached to this GameObject (null if there is none attached).附加在本游戏对象上的AudioSource(没有则为null).guiText The GUIText attached to this GameObject (null if there is none attached).附加在本游戏对象上的GUIText(没有则为null).networkView The NetworkView attached to this GameObject (Read Only). (null if there is none attached)附加在本游戏对象上的NetworkView(只读)(没有则为null).guiTexture The GUITexture attached to this GameObject (Read Only). (null if there is none attached)附加在本游戏对象上的GUITexture(只读) (没有则为null).collider The Collider attached to this GameObject (null if there is none attached).附加在本游戏对象上的Collider(没有则为null).hingeJoint The HingeJoint attached to this GameObject (null if there is none attached).附加在本游戏对象上的HingeJoint(没有则为null).particleEmitter The ParticleEmitter attached to this GameObject (null if there is none attached).附加在本游戏对象上的ParticleEmitter(没有则为null).gameObject The game object this component is attached to. A component is always attached to a game object.该组件附加的游戏对象.组件总是附加在一个游戏对象上.tag The tag of this game object.该游戏对象的标签.name The name of the object.该游戏对象的名字.hideFlags Should the object be hidden, saved with the scene or modifiable by the user?设置是否隐藏,保存在场景中或被用户修改.Inherited Functions 被继承的函数GetComponent Returns the component of Type type if the game object has one attached, null if it doesn't.返回游戏对象上某类型的组件.没有则返回null.GetComponentInChildren Returns the component of Type type in the GameObject or any of its children using depth first search.返回游戏对象或其子物体上某类型的组件.没有则返回null.搜素时深度优先.GetComponentsInChildren Returns all components of Type type in the GameObject or any of its children.返回游戏对象或其子物体上所有某类型的组件GetComponents Returns all components of Type type in the GameObject.返回游戏对象上某类型的所有组件.CompareTag Is this game object tagged tag?核对游戏对象的标签SendMessageUpwards Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the Behaviour在该游戏对象的所有MonoBehaviour上及其父物体上调用名为methodName的方法,SendMessage Calls the method named methodName on every MonoBehaviour in this game object.在该游戏对象的所有MonoBehaviour上调用名为methodName的方法,BroadcastMessage Calls the method named methodName on every MonoBehaviour in this game object or any of its children.在该游戏对象的所有MonoBehaviour上及其子物体上调用名为methodName的方法,GetInstanceID Returns the instance id of the object.返回该物体的实例ID.Inherited Class Functions 被继承的类函数operator bool Does the object exist?判断物体是否存在.Instantiate Clones the object original and returns the clone.复制一个物体并返回该备份.Destroy Removes a gameobject, component or asset.移除一个物体,组件或资源.DestroyImmediate Destroys the object obj immediately. It is strongly recommended to use Destroy instead.立刻销毁一个物体.建议用Destroy代替之.FindObjectsOfType Returns a list of all active loaded objects of Type type.返回找到的所有指定类型的对象.FindObjectOfType Returns the first active loaded object of Type type.返回找到的指定类型的第一个对象operator ==Compares if two objects refer to the same比较两个物体是否相同.operator !=Compares if two objects refer to a different object比较两个物体是否不同.DontDestroyOnLoad Makes the object target not be destroyed automatically when loading a new scene.确保目标对象在加载新场景时不被自动销毁.eGUILayoutDescriptionDisabling this lets you skip the GUI layout phase.禁用此项,将会跳过GUILayout部署阶段It can only be used if you do not use GUI.Window and GUILayout inside of this OnGUI call.它只用于在假如你不用GUI.Window和GUILayout的时候.MonoBehaviour.Invokefunction Invoke (methodName : string, time : float) : voidDescriptionInvokes the method methodName in time seconds.根据时间调用指定方法名的方法.JavaScript// Launches a projectile in 2 seconds// 2秒后发射炮弹var projectile : Rigidbody;Invoke("LaunchProjectile", 2);function LaunchProjectile () {var instance : Rigidbody = Instantiate(projectile);instance.velocity = Random.insideUnitSphere * 5;}MonoBehaviour.InvokeRepeatingfunction InvokeRepeating (methodName : string, time : float, repeatRate : float) : voidDescriptionInvokes the method methodName in time seconds.根据时间调用指定方法名的方法After the first invocation repeats calling that function every repeatRate seconds. 从第一次调用开始,每隔repeatRate时间调用一次.JavaScript// Starting in 2 seconds.// a projectile will be launched every 0.3 seconds// 2秒后开始// 每0.3秒发射一颗炮弹var projectile : Rigidbody;InvokeRepeating("LaunchProjectile", 2, 0.3);function LaunchProjectile () {var instance : Rigidbody = Instantiate(projectile);instance.velocity = Random.insideUnitSphere * 5;}MonoBehaviour.CancelInvokefunction CancelInvoke () : voidDescriptionCancels all Invoke calls on this MonoBehaviour.取消这个MonoBehaviour上的所有调用.JavaScript// Starting in 2 seconds.// a projectile will be launched every 0.3 seconds// 2秒后开始// 每0.3秒发射一颗炮弹var projectile : Rigidbody;InvokeRepeating("LaunchProjectile", 2, 0.3);// Cancels the repeating invoke call,// when the user pressed the ctrl button// 当用户按下ctrl键取消repeating调用function Update() {if (Input.GetButton ("Fire1"))CancelInvoke();}function LaunchProjectile () {instance = Instantiate(projectile);instance.velocity = Random.insideUnitSphere * 5;}function CancelInvoke (methodName : string) : voidDescriptionCancels all Invoke calls with name methodName on this behaviour.取消所有名为methodName的调用.JavaScript// Starting in 2 seconds.// a projectile will be launched every 0.3 seconds// 2秒后开始// 每0.3秒发射一颗炮弹var projectile : Rigidbody;InvokeRepeating("LaunchProjectile", 2, 0.3);// Cancels the repeating invoke call,// when the user pressed the ctrl button// 当用户按下ctrl键取消repeating调用function Update() {if (Input.GetButton ("Fire1"))CancelInvoke("LaunchProjectile");}function LaunchProjectile () {instance = Instantiate(projectile);instance.velocity = Random.insideUnitSphere * 5;}MonoBehaviour.IsInvokingDescriptionIs any invoke on methodName pending?某指定函数是否在等候调用.JavaScript// Instantiates a project after 2 seconds when Space key was pressed// and it will only call the function after the function has ended its execution // 按下空格键2秒后实例化一个炮弹,在该函数执行完毕之前仅调用此函数var projectile : Rigidbody;function Update() {if(Input.GetKeyDown(KeyCode.Space) && !IsInvoking("LaunchProjectile"))Invoke("LaunchProjectile", 2);}function LaunchProjectile () {var instance : Rigidbody = Instantiate(projectile);instance.velocity = Random.insideUnitSphere * 5;}function IsInvoking () : boolDescriptionIs any invoke pending on this MonoBehaviour?此MonoBehaviour上是否有调用在等候.MonoBehaviour.StartCoroutinefunction StartCoroutine (routine : IEnumerator) : CoroutineDescriptionStarts a coroutine.开始协同程序.The execution of a coroutine can be paused at any point using the yield statement. The yield return value specifies when the coroutine is resumed. Coroutines are excellent when modelling behaviour over several frames. Coroutines have virtually no performance overhead. StartCoroutine function always returns immediately, however you can yield the result. This will wait until the coroutine has finished execution.一个协同程序在执行过程中,可以在任意位置使用yield语句.yield的返回值控制何时恢复协同程序向下执行.协同程序在对象自有帧执行过程中堪称优秀.协同程序在性能上没有更多的开销.StartCoroutine函数是立刻返回的,但是yield可以延迟结果.直到协同程序执行完毕.When using JavaScript it is not necessary to use StartCoroutine, the compiler will do this for you. When writing C# code you must call StartCoroutine.用javascript不需要添加StartCoroutine,编译器将会替你完成.但是在C#下,你必须调用StartCoroutine.JavaScript// In this example we show how to invoke a coroutine and continue executing// the function in parallel.// 此例演示如何调用协同程序和它的执行function Start() {// - After 0 seconds, prints "Starting 0.0"// - After 0 seconds, prints "Before WaitAndPrint Finishes 0.0"// - After 2 seconds, prints "WaitAndPrint 2.0"// 先打印"Starting 0.0"和"Before WaitAndPrint Finishes 0.0"两句,2秒后打印"WaitAndPrint 2.0"print ("Starting " + Time.time);// Start function WaitAndPrint as a coroutine. And continue execution while it is running // this is the same as WaintAndPrint(2.0) as the compiler does it for you automatically // 协同程序WaitAndPrint在Start函数内执行,可以视同于它与Start函数同步执行.StartCoroutine(WaitAndPrint(2.0));print ("Before WaitAndPrint Finishes " + Time.time);}function WaitAndPrint (waitTime : float) {// suspend execution for waitTime seconds// 暂停执行waitTime秒yield WaitForSeconds (waitTime);print ("WaitAndPrint "+ Time.time);}Another Example:JavaScript// In this example we show how to invoke a coroutine and wait until it// is completed// 在这个例子中我们演示如何调用协同程序并直到它执行完成.function Start() {// - After 0 seconds, prints "Starting 0.0"// - After 2 seconds, prints "WaitAndPrint 2.0"// - After 2 seconds, prints "Done 2.0"// 0秒时打印"Starting 0.0",2秒后打印"WaitAndPrint 2.0"和"Done 2.0"print ("Starting " + Time.time);// Start function WaitAndPrint as a coroutine. And wait until it is completed.// the same as yield WaitAndPrint(2.0);// 运行WaitAndPrint直到完成yield StartCoroutine(WaitAndPrint(2.0));print ("Done " + Time.time);}function WaitAndPrint (waitTime : float) {// suspend execution for waitTime seconds// 等待waitTime秒yield WaitForSeconds (waitTime);print ("WaitAndPrint "+ Time.time);}function StartCoroutine (methodName : string, value : object = null) : CoroutineDescriptionStarts a coroutine named methodName.开始一个叫methodName的协同程序.In most cases you want to use the StartCoroutine variation above. However StartCoroutine using a string method name allows you to use StopCoroutine with a specific method name. The downside is that the string version has a higher runtime overhead to start the coroutine and you can pass only one parameter很多情况下,我们会用到StartCoroutine的一个变体.使用有字符串方法名的StartCoroutine允许你用StopCoroutine去停止它.其缺点就是会有较高的性能开销,而且你只能传递一个参数.JavaScript// In this example we show how to invoke a coroutine using a string name and stop it// 这个例子演示如何调用一个使用字符串名称的协同程序并停掉它function Start () {StartCoroutine("DoSomething", 2.0);yield WaitForSeconds(1);StopCoroutine("DoSomething");}function DoSomething (someParameter : float) {while (true) {print("DoSomething Loop");// Yield execution of this coroutine and return to the main loop until next frame// 停止协同程序的执行并返回到主循环直到下一帧.yield;}}MonoBehaviour.StopCoroutinefunction StopCoroutine (methodName : string) : voidDescriptionStops all coroutines named methodName running on this behaviour.停止这个动作中名为methodName的所有协同程序.Please note that only StartCoroutine using a string method name can be stopped using StopCoroutine.请注意只有StartCoroutine使用一个字符串方法名时才能用StopCoroutine停用之.JavaScript// In this example we show how to invoke a coroutine using a string name and stop it// 这个例子演示如何调用一个使用字符串名称的协同程序并停掉它function Start () {StartCoroutine("DoSomething", 2.0);yield WaitForSeconds(1);StopCoroutine("DoSomething");}function DoSomething (someParameter : float) {while (true) {print("DoSomething Loop");// Yield execution of this coroutine and return to the main loop until next frame // 停止协同程序的执行并返回到主循环直到下一帧.yield;}}MonoBehaviour.StopAllCoroutinesfunction StopAllCoroutines () : voidDescriptionStops all coroutines running on this behaviour.停止所有动作的协同程序.JavaScript// Starts the coroutine// 开始协同程序.StartCoroutine ("DoSomething");// Cancels the coroutine immediately afterwards// 随后立即取消之.function DoSomething () {while (true) {yield;}}StopAllCoroutines();MonoBehaviour.Updatefunction Update () : voidDescriptionUpdate is called every frame, if the MonoBehaviour is enabled.当MonoBehaviour启用时,其Update在每一帧被调用Update is the most commonly used function to implement any kind of game behaviour.Update是实现各种游戏行为最常用的函数.JavaScript// Moves the object forward 1 meter a second// 以每秒1米的速度向前移动物体function Update () {transform.Translate(0, 0, Time.deltaTime * 1);}In order to get the elapsed time since last call to Update, use Time.deltaTime. This function is only called if the Behaviour is enabled. Override this function in order to provide your component's functionality.为了获取自最后一次调用Update所用的时间,可以用Time.deltaTime.这个函数只有在Behaviour启用时被调用.实现组件功能时重载这个函数.teUpdatefunction LateUpdate () : voidDescriptionLateUpdate is called every frame, if the Behaviour is enabled.当MonoBehaviour启用时,其LateUpdate在每一帧被调用LateUpdate is called after all Update functions have been called. This is useful to order script execution. For example a follow camera should always be implemented in LateUpdate because it tracks objects that might have moved inside Update.LateUpdate是在所有Update函数调用后被调用.这可用于调整脚本执行顺序.例如:当物体在Update里移动时,跟随物体的相机可以在LateUpdate里实现,JavaScript// Moves the object forward 1 meter a second// 以每秒1米的速度向前移动物体function LateUpdate () {transform.Translate(0, 0, Time.deltaTime * 1);}In order to get the elapsed time since last call to LateUpdate, use Time.deltaTime. This function is only called if the Behaviour is enabled. Override this function in order to provide your component's functionality.为了获取自最后一次调用LateUpdate所用的时间,可以用Time.deltaTime.这个函数只有在Behaviour启用时被调用.实现组件功能时重载这个函数.MonoBehaviour.FixedUpdatefunction FixedUpdate () : voidDescriptionThis function is called every fixed framerate frame, if the MonoBehaviour is enabled.当MonoBehaviour启用时,其FixedUpdate在每一帧被调用.FixedUpdate should be used instead of Update when dealing with Rigidbody. For example when adding a force to a rigidbody, you have to apply the force every fixed frame inside FixedUpdate instead of every frame inside Update.处理Rigidbody时,需要用FixedUpdate代替Update.例如:给刚体加一个作用力时,你必须应用作用力在FixedUpdate里的固定帧,而不是Update中的帧.(两者帧长不同)JavaScript// Apply a upwards force to the rigid body every frame// 每帧应用一个向上的力到刚体上function FixedUpdate () {rigidbody.AddForce (Vector3.up);}In order to get the elapsed time since last call to FixedUpdate, use Time.deltaTime This function is only called if the Behaviour is enabled. Override this function in order to provide your component's functionality.为了获取自最后一次调用FixedUpdate所用的时间,可以用Time.deltaTime.这个函数只有在Behaviour启用时被调用.实现组件功能时重载这个函数.MonoBehaviour.Awakefunction Awake () : voidDescriptionAwake is called when the script instance is being loaded.当一个脚本实例被载入时Awake被调用.Awake is used to initialize any variables or game state before the game starts. Awake is called only once during the lifetime of the script instance. Awake is called after all objects are initialized so you can safely speak to other objects or query them using eg. GameObject.FindWithTag. Each GameObject's Awake is called in a random order between objects. Because of this, you should use Awake to set up references between scripts, and use Start to pass any information back and forth. Awake is always called before any Start functions. This allows you to order initialization of scripts. Awake can not act as a coroutine.Awake用于在游戏开始之前初始化变量或游戏状态.在脚本整个生命周期内它仅被调用一次.Awake在所有对象被初始化之后调用,所以你可以安全的与其他对象对话或用诸如GameObject.FindWithTag这样的函数搜索它们.每个游戏物体上的Awke以随机的顺序被调用.因此,你应该用Awake来设置脚本间的引用,并用Start来传递信息Awake总是在Start之前被调用.它不能用来执行协同程序.Note for C# and Boo users: use Awake instead of the constructor for initialization, as the serialized state of the component is undefined at construction time. Awake is called once, just like the constructor.C#和Boo用户注意:Awake不同于构造函数,物体被构造时并没有定义组件的序列化状态.Awake像构造函数一样只被调用一次.JavaScriptprivate var target : GameObject;function Awake () {target = GameObject.FindWithTag ("Player");}Awake cannot be a co-routine.Awake不能用作协同程序.MonoBehaviour.Startfunction Start () : voidDescriptionStart is called just before any of the Update methods is called the first time.Start仅在Update函数第一次被调用前调用Start is only called once in the lifetime of the behaviour. The difference between Awake and Start is that Start is only called if the script instance is enabled. This allows you to delay any initialization code, until it is really needed. Awake is always called before any Start functions. This allows you to order initialization of scripts.Start在behaviour的生命周期中只被调用一次.它和Awake的不同是Start只在脚本实例被启用时调用.你可以按需调整延迟初始化代码.Awake总是在Start之前执行.这允许你协调初始化顺序.The Start function is called after all Awake functions on all script instances have been called.在所有脚本实例中,Start函数总是在Awake函数之后调用.JavaScript// Initializes the target variable.// target is private and thus not editable in the inspector// 初始化目标变量// 目标是私有的并且不能在检视面板中编辑private var target : GameObject;function Start () {target = GameObject.FindWithTag ("Player");}MonoBehaviour.Resetfunction Reset () : voidDescriptionReset to default values.重置为默认值Reset is called when the user hits the Reset button in the Inspector's context menu or when adding the component the first time. This function is only called in editor mode. Reset is most commonly used to give good default values in the inspector.Reset是在用户点击检视面板的Reset按钮或者首次添加该组件时被调用.此函数只在编辑模式下被调用.Reset最常用于在检视面板中给定一个最常用的默认值.JavaScript// Sets target to a default value.// This could be used in a follow camera.// 设置target为默认值// 这可以用于一个跟踪相机var target : GameObject;function Reset () {// Only set target if it is not assigned yet.// 如果target没有赋值,设置它if (!target)target = GameObject.FindWithTag ("Player");}MonoBehaviour.OnMouseEnterfunction OnMouseEnter () : voidDescriptionOnMouseEnter is called when the mouse entered the GUIElement or Collider.当鼠标进入到GUIElement(GUI组件)或Collider(碰撞体)中时调用OnMouseEnter.JavaScript// Attach this script to a mesh to make// it red when the mouse is over the mesh// 附加这个脚本到网格// 当鼠标经过网格时网格变红色function OnMouseEnter () {renderer.material.color = Color.red;}This function is not called on objects that belong to Ignore Raycast layer.OnMouseEnter can be a co-routine, simply use the yield statement in the function. This event is sent to all scripts attached to the Collider or GUIElement.这个函数不会在属于Ignore Raycast的层上调用.它可以被作为协同程序,在函数体内使用yield语句.这个事件将发送到所有附在Collider或GUIElement的脚本上.IMPORTANT: This function has no effect on iPhone.注意:这个函数在Iphone上无效.MonoBehaviour.OnMouseOverfunction OnMouseOver () : voidDescriptionOnMouseOver is called every frame while the mouse is over the GUIElement or Collider.当鼠标悬浮在GUIElement(GUI组件)或Collider(碰撞体)上时调用OnMouseOver.JavaScript// Fades the red component of the material to zero// while the mouse is over the mesh// 当鼠标在网格上时渐变红色组件为0function OnMouseOver () {renderer.material.color -= Color(0.1, 0, 0) * Time.deltaTime;}This function is not called on objects that belong to Ignore Raycast layer.OnMouseOver can be a co-routine, simply use the yield statement in the function. This event is sent to all scripts attached to the Collider or GUIElement.这个函数不会在属于Ignore Raycast的层上调用.它可以被作为协同程序,在函数体内使用yield语句.这个事件将发送到所有附在Collider或GUIElement的脚本上.IMPORTANT: This function has no effect on iPhone.注意:此函数在iPhone上无效.MonoBehaviour.OnMouseExitfunction OnMouseExit () : voidDescriptionOnMouseExit is called when the mouse is not any longer over the GUIElement or Collider.当鼠标移出GUIElement(GUI组件)或Collider(碰撞体)上时调用OnMouseExit.OnMouseExit balances out OnMouseEnterOnMouseExit与OnMouseEnter相反.JavaScript。
unity 3D 课件 第02章 Unity脚本程序基础知识
2.3 Unity脚本的基础语法
2.3.6 成员变量和全局变量 定义在方法体外的变量是成员变量,可以在属性查看器看到,读者可 以随时在属性查看器中修改它的值。通过private创建的变量是私有变 量,这些在属性查看器中就不会显示该变量
第13页
2.3 Unity脚本的基础语法
2.3.6 成员变量和全局变量
第18页
2.3 Unity脚本的基础语法
2.3.9 一些重要的类 1. MonoBehaviour类 MonoBehaviour 类 是 C# 脚 本 的 基 类 , 其 继 承 自 Behaviour类。在C#脚本中,必须直接或间接的继承 MonoBehaviour类 2. Transform类 场景中的每一个物体都有一个 Transform 组件,它就 是 Transform 类实例化的对象。用于储存并操控物体 的位置、旋转和缩放。每一个 Transform 可以有一个 父级,允许分层次应用位置、旋转和缩放。可以在 Hierarchy 面板查看层次关系。 Transform 类中包含
返回两个向量中长度较小的向量。 Max
返回两个向量中长度较大的向量。
operator ==
两个向量是否相等
operator !=
SmoothDamp
两个向量是否不相等
随着时间的推移,逐渐改变一个 向量朝向预期的目标。
ClampMagnitude 返回向量的长度,最大不超过 第12页 maxLength所指示的长度。
2.3 Unity脚本的基础语法
2.3.2 记录时间 记录时间需要用到Time类 ,Time类中比较重要的变 量为deltaTime它指的是从最近一次调用Update或者 FixedUpdate方法到现在的时间 具体开发流程如下。 (1)创建Cube对象。点击 GameObject→3DObject→Cube (2)编写脚本。在Assets面板点击Create→C# Script。 (3)挂载脚本。脚本开发完成后,将这个脚本挂载 到游戏对象上 。
Unity3D入门中文教程
Unity3D 基本操作1. 建模中使用的图片、文件、文件夹等以及模型中物体、材质等的名称都不能使用中文或者特殊符号,可以使用英文字母、数字、下划线等 2. 调整Max 的单位为米3. 烘培光影的设置4•模型的中的植物效果,第一种是单面片植物,需要设置其轴心为其物体的对 称中心;第二种是十字交叉的植物效果;第三种则是到 Un ity3D 编辑器中通过地形编辑器系统添加基本设置5. Fbx 导出插件下载地址:/adsk/servlet/item?sitelD=123112&id=10775855 6. 将Max 文件中用到的图片都拷贝到Textures 目录下,如Textures2005-6-3 101577. 再打开Max 文件,导出为FBX 文件,使用默认设置, 文件相同的目录下,如dirnan.FK 2009-6-10 19:Q5 FEM文件louFana ,F0X 200SH&-10 I9t :27 F0X Stft导出的时候,可以将模型简单的分类,如地面、植被、楼房等,也可以将模型 分为几个区域,如小区1,小区2,学校等等分开导出8. 将包含Max 文件、Fbx 文件和Textures 文件夹的文件夹拷贝到 Unity3D 项目的Assets 目录下,如下图中红圈FBX 文件也放置在和Maxtree. FBXZ009-6-1Q I9;Q5 FBX 文件Sdsniax scene FileTextures2009-6-3 ]0:572009-&-S 23:32 3dsma?c scene file IZ009-&-10 I9:Z7?鈕型目空立蛊f 區地址(Q) | O C: \LlnityPro(ect\SewerProject^.Prefabs _5haders在下一次用Unity3D 编辑器开启本项目的时候,编辑器将自动导入 夹中的信息,并生成 Materials 文件夹,如9. 启动Unity3D 编辑器10. 选择刚才拷贝进来的文件中的Fbx 文件,如修改其中的 Meshes 下的 Scale Facto 和 Gen erate Colliders ,如B maya5wat匚hes_Materials十」_ObjedsArtworks Editor-P F 口StandardA^^etsStandard Assets.Scenes_5ou nds/更新该文件B M I 20 29-6-5 Z3□二3dvTiaj ^crlirI MatrlU^(J 2009^6 ■ 10 W:07dr>«n 用工FBK 殳件 Idf 呂叩戶駄20D9-6-L019 27FBK 更件20^-firiaig osFM^fPSfi'imait"" Eom-ft-ioig 27:创埶亜一型!点击其他Fbx文件或者单击其他区域将弹出如下的对话框Un让# AlrrtUnapplied import settingsUnapplied impart settings for 'Assets/SjVang/Artworks/dimian.FBX'Revert点击Apply即可,类似的方式设置其他Fbx文件注意,其中植物/植被类的Fbx文件不需要设置Gen erate Colliders项11. 将Fbx文件直接拖放到Hierarchy区域,女口12. 点击Hierarchy 区域中的对象,同时将鼠标移动三维显示区域,同时点击键 ,则该对象自动适配显示到三维区域中心,如13. 将全部fbx 添加完成后,提高场景亮度如下-nfx|Fie EditAssets Campamt lerrain UAndow Help[Laytsr[ G 料u(O InipcctorLhii 些"j D«r *ulET 严. TransliarmRosltlainQ *.X :!V :!2 DX ov 0 2 D5皿X 1T 厂•j iT Q 0 An^mailiQii Aninuti 口 斛►AnlmatlonjWrap iwode Pfary AutDrndrticflllY AnirtUEe Pfiy&icifil'dNone (Animzilion Clip] M Dtfault;T O CFBNlmportcn 6Meshesin^pcdfioom lappEdRoorn Q g wwrEkidlmlan・ I j^laufding k Q Materials> ^Tektures5cale F^Elia-r IGefKTiiteCcIlKfcrs : @ CAkulm Normals 匚 5nnoadi<ing Ang^(50—5pll 【TangenU □Sw^ UVi □Ma[«rlaJsGcnc-riwtiCin m 仙讪亡包Ejth LiG4d lUEurfl cruias oiwfnatiwul.17档血 KVlEhsarrw-lexiure will J I SD use the same nwneriaJ.it UhiiLy - Untitled -I0Q105n<ap Settbigs...Ed!P.erdet Setting34 空 ErrnJ 鲨imMet™kEmtooiiCopy P-asteDelete PauseStephjme •詔 ected Sfitect Al Sdtve SeledionAssets GameObjEscI: Component Terran Wiidow He|pUndo Sebition Change Qrl+ZQrl+yPreferences-..-Ori+xQri-K Qrl+V Locd ]・■ *1 | L^putQrl-HDStlft+DftlFCtri+AQrl+PCtri+5hft+PQrl+Afc+PRert|»==Hlertirchv ・ dlntian• loufang Main Camera ► treeG Inspecxcrf ⑨ Fag Fagi-Cclar Fag Density Ambient Light 5k¥box Material Halo Strength Fibre Strength Hula T EKture Spel Cookiefi<mdrr Salti ngs 4 魅nckir 条物町斗匚 0□JO]None (Mateirldb + 0.5 1None (Te-Hture 2D) TNone rrgxEure 20) TCJ Prajetl€i AJKti ■► f t Editor<3 LiglhtM-iipp^d Rapm ■Liglh Mapped Roam> CSuYangT LjArtWOrksdin賈焉单击 Ambient Light ,如下 调整为匚olor ES▼ ColorsSliders即可设置完成14.设置第一人称浏览删除场景中Ma in Camera将Project区域的Standard Assets下的Prefabs下的First Person Controller 拖到Hierarchy 区域中点选First Pers on Con troller,调整First PersonController的位置到场景中合适的位置,并设置其高度为 1.37到2.1左右设置First Person Controller的高度在场景中地面之上15•点击运行,即可测试C+ Unity Untitled 5uy<mg* -fl £is Edit Assists (ia™0bje戊Component Terrisin iBndcwf 践ip卩MH hkErarciiy►diimijin・Fjrsl Person Conlroller ►k?ufan^i[La 祝r LD lin^prctorR [ L^youiT 二H:Al-pw lI li ProjectCrute •• ZlEdlcor► ZSJLiOthMappcdSoorn ¥ 为Stun日列d AsvchT 豈Prehb%►Ij.1 First RsriOrt f otKFnll色i 卜口呂0b-生hdjdaiiM► ^Carne raScflpts• QFonrtKk bight Q口dkiu*ik Q Light Flaie-s.•左|PM【i日刨►口內vr引i Mdier ial^► ±]5<rlpt5► ^]SkytoKe-sk UlTu IT win Grof &MaiMELotikxs - Llnt5d<TE 5M二gfjj修改视角控制键为右键16. 打开Project 区域中的StandardAssets下的CameraScripts下的MouseLook脚本,在在Quater nion origi nalRotatio n;void Update (){if (axes == Rotatio nAxes.MouseXA ndY) {// Read the mouse in put axis中添加一行代码修改为Quaternion originalRotation;void Update (){if(I nput.GetAxis ("Fire2")==0) return;if (axes == Rotatio nAxes.MouseXA ndY) {// Read the mouse in put axis如何取消浏览窗口上的右键菜单只要设置Unity 对象的参数即可禁止右键菜单的显示,如下:vobject id="U nityObject" classid="clsid:444785F1-DE89-4295-863A-D46C3A781394"width="600" height="450"a# ibr. X • zQ 甲皤• n n ,1 LfJWl▼ 1 [ L^|fw!IMousdjc^-.cs 1*1= LHitIdrcJrT |publte 什0>曲耳en 引询即兀=15F; 丄1 pul>l^ Ooal = 15F;Dupllahc Waur (rirmlinruil lighljrMrrrHnn^l llnhr* Q M DUM ikMk iMarH> SfrljHi 1 皿岳■ Apublic naal public Mom=・360F;m^rilmuinx = 3MFjpublic Mo 白I public IILaat mirirtiLmY = -MF; marilmumiY 二 6Dfj-rifrdt mtatenK = OF; Float ratatkiriY = UF;Quaterrii^测牛和沖心悒诚n; vwd Update ()\l (asei -= mjaidLiart^r-fis.M&jseXAmdV}// feiiid "|w H»d5fr lf¥-ut dxLrraifttiCKlK 4 ・ JrtpuiLGe!CAKilCMau5.e X B ) '* 弓esfi 引tiwityXji4 鼻 InpuE.G 自t 虫Ki£f ・MtiLi5■巴 V ') * SAAiilEiuiEy-^^ralatiodk ■ ClampAng^e (roC -alidriXj minihium^ 丽BKiftiuniK 片 ralaticnV ■ ClampAngfe (rotaliQriyj minimufiiYjg i^idKkTiuni<'¥T firGEPttridii CfihlfOlltrGr-iphics in Camera ft>int light Pulnc iKjhc hint IlghE Point light hilnc lighc mint light Pnlnc lipht f^lnE light Pnlnc Ilghi fclllE light Rjlnt light打丿 MpuMLwk rptftri tr^ni^rin an themaus< drita.J// Miniwjiw ar (d «4aK««ur« v-alues can be UV^I B tQnWun thf RMibl 痔R* T Q ™lw «n> FF5 style cAiiracHr: 打J ■ ■西電iwW/// - Add J rigd bodr co O H cjpiiik 打 J - Add chs MouseljDok Krlpt bo t*w ■电 Mvk ; /// -> Sci the tnodse bet. u> LookX. 网H want t& wi>¥ iurn dhuoc 悚r but nw Rlk 训 ///-Add FPSiMilkAr tmpC ED ihe capsuleQuat^rnidrl KQuAtmififi ■ QualHniDn.Angle-AKis (rDtaUcin^ VrctorS.up^ QuaCernun yQj^Cernhn - Qudterman-An^eAxia (ral-atinnY^ Vec?口「aiisl'L 片I UghllimF Wj«hEr • |^54UfCK .2J&UridArdAhMh T 口 Prtfabi-■ IjjFlrsi 您口叶 Ucmijrol ■& .Q M4ln C4mf r 4 ljjGrapliiC5• ^ifllob-$had<ni w 上二厂“TT^rx 崎rrln ・tJ f .1 - CrvriEr di Ramark kVikv ih^ c^iirtHi ■ A chM af che upsult R MH *节 translorm. Jf F ■ Add 4 HciU^rlDQk TC«PC RD lhe CDmerB. w -k- -Stl lh* i*A&uh* I LW A lit uM LA£ik¥ i¥ou 卿m the Ejnwj ID dh up md down like B h<Hd, Th* tkarKter ilrMdv turnsJ|AddCOri1p4>fMifi[M<*rtu{"CMttra-C-Ohl/^.l I4d U54 soldi puWlC ells-!! WbKnitlTOk MQilWDthffrlOUr 155 kuuirtfilikpublic efivm R XMUK ^H A MCS - I Mous^XAndT ♦ Ck 盘■何-].MwstV ■ P ]pubIM RouiianAket au<i - Rau.WfiA»e5Mou5eXAnd¥:ERibk iiengibVitKl ■ 15-F.public H UM fensiovkyY ■ 3 5-f;trara-Farm 」□匚dRotadan ■ onginalRDtadon *■ KQu -alemim ■*■ yQuaternian' else rf (ac-es - - RDtahanAxes.Mausr^)ratationX ■+ ■ jnput.GElzAKifCMause X') " sensitiwity-X; rataticnX « 亡lampAngle (rota^IianXj. mnirnum^, imaKimuniX)i-[jSnMMxhFolQ^ |i | SmoothLwkAt k ^Fonti■ 口Whl C-Dubrh* CjLighi FiarH■El ^r»l«n ㈣ riH cruhed MI k lasc sc.publ< mmniumX ™ - publfilDMrYUNlmumX ■吕EOF;U9.ng HJnitYLngne :*!iProi4£[pubis Hnat mnimiimY piibtellDK rvuNlmumV植物效果设置17. 对于单面片的植物效果,需要设定其材质为Tran spare nt/VertexLit类型,并为其添加公告板脚本设定前设置材质类型为Tran spare nt/VertexLit类型,如下给单面片植物添加公告板脚本的方法是先选择该植物,然后点击菜单compo nen t下的scripts 下的camera Facing Billboard 即可,如下设置材质类型和添加公告板脚本后,如下如果没有该脚本组件,可以打开脚本编辑器,拷贝如下代码到脚本中,保存到Assets'Scripts 下,命名为CameraFacingBillboard.cs 即可using Uni tyE ngine;using System.Collectio ns;public class CameraFaci ngBillboard : Mon oBehaviour {|public Camera cameraToLookAt;void Start(){cameraToLookAt=Camera.main;}void Update(){IVector3 v = cameraToLookAt.tra nsform.positio n - tran sform.positio n; v.x = v.z =0.0f;tran sfor m. LookAt(cameraToLookAt.tra nsform.positio n - v);}}18.对于十字交叉的植物,需要将其材质设定为Nature/VegetationTwo Passunlit类型设置前的效果设置后的效果水面效果的设置19.创建一个网格面片詐Unity - suyangl.unity - suy^ng* 亠丨口|搭1 Ale Edit AsseCs GamBObject Cotrsponenfi Terr an Window HdpC Gam?e 伽讪ed ■H 匚enter [® Local左Hierarchy► dUvnlan卜First Person Co-ntrollerPlane・ Ercc4 Project* I►^Camera Scripts►~~d Fonts►1~ Light Cookies庄^Light Flares 二旳口记I好・Physic Materials►^Scripts►^gSlqr boxes氐"nTerram Grass'Terrain Tu 寓匸uFt予►^jTrees Ambient-OcclusiiDn TZwater.jJ Daylight Simple WaterLivers・f Layout Hl:*6 InEp-cctor T =7 PiantT人TransformPmiilonC *TX -1053.96fi Y 15^2192 Z -N11.259RotationX 0 ¥ 0Z 0Scale| X 1 V 1;Z 1T ;■;Plan-e tMesliFiller)Mesh爲Plane.:Mesh collider匸枕Material None (Physic Mate rial;T!§. TriggerSmooth Sphere 匚ollisJcm%□ConvexMwh囲Plane T审曲* Mesh RcndererCa^t ShadowsRecsrve Shadows Mj T Materials.Size1Element 0m Dcfau k- DiFfu'sc “Tag I Untagged I I Layer Defill:・20.给该水面面片设置水材质和水脚本,如即可烘培光影贴图的处理21. Unity3D光影烘培的要求U3D的光影贴图使用的是3Dmax中的标准材质的自发光贴图通道来存储光影贴图相关参数,如22. 给每个物体都附上贴图,如果是纯色物体,也付给纯色贴图23. 打光后,选择要烘培的物体卜」z 嚼廿fiTiir:比f 吐如I此试母讣.沁K JH'JFID耳附01旨IIB El Xi帝住|阿了 $MUBl紐吐古.懈询…目寻富时喪”■AdM'POOTiJ...鼻云上炖船WufT^t+HSA^BrtaiPJ-HAjftaMKHilli-mnl * r 巧灣■I ■ I v «4 ..1g m a>43b va Ip BD 3D ido[■mLZu.iMe: a>7 ] -i-STH;Q S x厂1厂M厂1H^ = JO a自曲■点|遠职豪±j MM 41 El ■> w Q蚩:M/P.d询恫酬嗣白i|滞T母百 / iHr-r.ij:B « |il基IAC缺站口上IEti阳跑釧tsn设置输出路径添加烘培输出的贴图类型24.Unity 基础本部分是你开始Unity 的关键。
Unity3D中文手册
957F 5B B D 9A D8957F 5B B D 9A D 8 957F 5B B D 9A D 8Unity3D 中文手册User Manual(内部培训教材)译:Nette长宽高(北京)科技有限公司957F 5B B D 9A D8957F 5B B D 9A D 8 957F 5B B D 9A D 8说明:本文档所有资源均来自于互联网。
如果你对本文档中的内容有疑问请发送Email 到tianyhongcn@注意:本文档不包含组件参考和脚本参考的任何内容,它们将是另外的文档。
版权:1. 该文档属公司内部培训教程,不发行,不出版,仅作为公司内部的技术参考。
2. 本文档内容已申请著作权,受中国版权法保护,未经著作权人书面许可,本手册的任何部分不得以任何形式或手段复制或传播。
957F 5B B D 9A D8957F 5B B D 9A D 8 957F 5B B D 9A D 8目录欢迎使用Unity................................................................................................................................1 一、用户指南. (2)1.1. Unity 基础(Unity Basics) (2)1.1.1. 学习界面...........................................................................................................2 1.1.2. 资源工作流(Asset Workflow)........................................................................17 1.1.3. 创建场景(Creating Scenes)............................................................................18 1.1.4. 发布(Publishing Builds)..................................................................................19 1.1.5. 教程(Tutorials)................................................................................................22 1.2. 构建场景(Building Scenes) (23)1.2.1. 游戏物体(GameObject)..................................................................................23 1.2.2. 使用组件(Using Components).......................................................................25 1.2.3. 预设(Prefab)....................................................................................................30 1.2.4. 光照(Lights)....................................................................................................33 1.2.5. 相机(Cameras)................................................................................................42 1.2.6. 粒子系统(Particle Systems)............................................................................46 1.2.7. 地形引擎指南(Terrain Engine Guide)............................................................59 1.3. 使用资源(Working with Assets).. (62)1.3.1. 导入资源(Importing Assets)...........................................................................63 1.3.2. 网格(Meshes)..................................................................................................65 1.3.3. 材质和着色器(Material and Shaders)............................................................69 1.3.4. 2D 纹理(Texture 2D)......................................................................................72 1.3.5. 电影纹理(Movie Texture)...............................................................................78 1.3.6. 音频文件(Audio Files)...................................................................................80 1.3.7. 使用脚本(Using Scripts).................................................................................84 1.3.8. 资源服务器指南(Assets Server Guide)..........................................................88 1.3.9. 场景背后(Behind the Scenes).........................................................................94 1.4. 创建游戏(Creating Gameplay). (94)1.4.1. 运行时实例化预设(Instantiating Prefabs at runtime)....................................95 1.4.2. 输入(Input)....................................................................................................100 1.4.3. 变换(Transforms)..........................................................................................102 1.4.4. 物理(Physics)................................................................................................107 1.4.5. 动画(Animation)...........................................................................................124 1.4.6. 角色动画(Character Animation)...................................................................126 1.4.7. 声音(Sound)..................................................................................................133 1.4.8. 游戏接口元素...............................................................................................138 1.4.9. 多人网络. (139)二、常见问题(FAQ) (141)2.1. 游戏编码问题 (141)2.1.1. 如何制作一个简单的第一人称行走...........................................................141 2.2. 图形问题 (141)957F 5B B D 9A D8957F 5B B D 9A D 8 957F 5B B D 9A D 82.2.1. 如何导入透明贴图.......................................................................................142 2.2.2. 如何使用凹凸贴图.......................................................................................144 2.2.3. 如何使用细节纹理.......................................................................................147 2.2.4. 如何制作立方体贴图纹理...........................................................................149 2.2.5. 如何制作天空盒...........................................................................................150 2.2.6. 如何制作网格粒子发射器...........................................................................151 2.2.7. 如何制作启动画面.......................................................................................152 2.2.8. 如何制作投射光Cookie..............................................................................153 2.2.9. 如何修正导入模型的旋转...........................................................................154 2.2.10. 如何使用水...................................................................................................155 2.3. 如何从3D 程序中导入物体.. (158)2.3.1. 从Maya 中导入物体....................................................................................158 2.3.2. 从Cinema 4D 导入物体...............................................................................159 2.3.3. 从3DMax 中导入物体.................................................................................161 2.3.4. 从Cheetah3D 中导入物体...........................................................................164 2.3.5. 从Modo 中导入物体...................................................................................164 2.3.6. 从Lightwave 中导入物体............................................................................165 2.3.7. 从Blender 中导入物体................................................................................168 2.4. 工作流问题.. (169)2.4.1. 如何在工程间重用资源...............................................................................169 2.4.2. 如何安装或更新标准资源 (169)三、高级 (171)3.1. 实时加载资源.......................................................................................................171 3.2. 通过脚本修改源资源...........................................................................................171 3.3. 更新顺序...............................................................................................................173 3.4. Unity 中的阴影.. (174)3.4.1. 直射光细节...................................................................................................175 3.4.2. 调试阴影.......................................................................................................180 3.4.3. 阴影大小计算...............................................................................................181 3.5. 优化图形性能. (182)3.5.1. 角色建模优化...............................................................................................183 3.5.2. 集成显卡优化...............................................................................................184 3.5.3. 渲染统计窗口...............................................................................................185 3.6. 减小文件尺寸.......................................................................................................186 3.7. 流式Web 播放.....................................................................................................189 3.8. Web 播放器部署.. (191)3.8.1. 加载Unity 内容的HTML 代码..................................................................191 3.8.2. 自定义Unity Web 播放器的加载场景........................................................192 3.8.3. 自定义Unity Web 播放器的行为................................................................194 3.8.4. Unity Web 播放器和浏览器通信.................................................................194 3.8.5. 使用浏览器脚本检测Unity Web 播放器....................................................196 3.8.6. 发布活动内容...............................................................................................199 3.9. Web 播放器调试..................................................................................................201 3.10. 插件——Pro 版特性.. (202)957F 5B B D 9A D8957F 5B B D 9A D 8 957F 5B B D 9A D 83.11. 建立播放器流水线...............................................................................................204 3.12. 着色器. (205)3.12.1. 着色器:开始...............................................................................................205 3.12.2. 着色器:顶点和片元程序...........................................................................210 3.13. 显卡模拟...............................................................................................................216 3.14. 网络模拟 (217)957F 5B B D 9A D8957F 5B B D 9A D 8 957F 5B B D 9A D 8欢迎使用UnityUnity 使用户能够创建最好的交互式娱乐或者多媒体体验,该手册被设计用于帮助你学习如何使用Unity ,从基础到高级技术。
Unity3D的脚本-script入门
Unity3D的脚本-script入门Unity3D的基本操作很容易就能掌握了,接下来就是游戏系统的核心部分:脚本。
什么是Script(脚本)?简而言之,就是使用代码来执行一系列动作命令的特殊文本,它需要编译器来从新解读。
U3D内部如何解读脚本,这不是我们所要关心的—这是引擎开发人员的活,我们所要知道的就是脚本的使用规则。
【三种语言的特点】U3D支持C#,JavaScript,BOO三种语言格式的代码编写。
首先来简单介绍下这三种语言的特点:对U3D来说,这是入门级的脚本语言,U3D内置的函数都能通过JS方便的调用。
语法上,JS和传统的C语言差不多,需要分号结束符,变量类型定义,大括号……不过它的变量类型定义,是通过冒号接在变量右边,如:Name:string=”Li”。
相对其他两种语言,使用JS 语法,很多函数不需要实例化就能直接使用,如:vector3 direction=vector3(1,2,3)。
如果使用C#,则需要使用new关键字:vector3 direction=new vector3(1,2,3)。
JavaScript直接继承自U3D的MonoBehaviour类,因此不像C#和BOO那样需要使用Using或Import来加载类库。
这看似省心,不过因为缺少了加载特殊类库,JavaScript能调用的第三方函数不多(当然,我们可以载入net类库给JavaScript调用,虽然看着有点奇怪……)。
*注意:JavaScript不是Java,同时,U3D中的JavaScript也有别于独立的JavaScript语言。
C#(发音C Sharp),微软开发的面向对象编程语言。
由于有强大的net类库支持,以及由此衍生出的很多跨平台语言,C#逐渐成为U3D开发者推崇的程序语言。
U3D内置的脚本范例中,C#脚本也占了很大一部分(其他脚本是JavaScript脚本)。
另外,在装有VisualStudio 的电脑上,我们也可以使用微软的脚本编辑工具来编写U3D脚本。
中文Unity3D脚本
Unity3D脚本参考概览运行时类附加姜凡2012-2-25一、脚本概览这是一个关于Unity内部脚本如何工作的简单概览。
Unity内部的脚本,是通过附加自定义脚本对象到游戏物体组成的。
在脚本对象内部不同志的函数被特定的事件调用。
最常用的列在下面:Update:这个函数在渲染一帧之前被调用,这里是大部分游戏行为代码被执行的地方,除了物理代码。
FixedUpdate:这个函数在每个物理时间步被调用一次,这是处理基于物理游戏的地方。
在任何函数之外的代码:在任何函数之外的代码在物体被加载的时候运行,这个可以用来初始化脚本状态。
注意:文档的这个部份假设你是用Javascript,参考用C#编写获取如何使用C#和Boo编写脚本的信息。
你也能定义事件句柄,它们的名称都以On开始,(例如OnCollisionEnter),为了查看完整的预定义事件的列表,参考MonoBehaviour 文档。
概览:常用操作大多数游戏物体的操作是通过游戏物体的Transform或Rigidbody来做的,在行为脚本内部它们可以分别通过transform和rigidbody访问,因此如果你想绕着Y轴每帧旋转5度,你可以如下写:function Update(){transform.Rotate(0,5,0);}如果你想向前移动一个物体,你应该如下写:function Update(){transform.Translate(0,0,2);}概览:跟踪时间Time类包含了一个非常重要的类变量,称为deltaTime,这个变量包含从上一次调用Update 或FixedUpdate(根据你是在Update函数还是在FixedUpdate函数中)到现在的时间量。
所以对于上面的例子,修改它使这个物体以一个恒定的速度旋转而不依赖于帧率:function Update(){transform.Rotate(0,5*Time.deltaTime,0);}移动物体:function Update(){transform. Translate (0, ,0,2*Time.deltaTime);}如果你加或是减一个每帧改变的值,你应该将它与Time.deltaTime相乘。
Unity3D中文菜单手册
Unity3D 命令手册MR.C 编制这本书主要对 Unity3D 来帮助大家初步的认识的所有菜单与参数进行了翻译Unity3D 的每个命令的作用并逐个讲解Unity3D 下分 8 个菜单栏(翻译的不一定准)分别是 File (文件) Edit (编辑) Assets(资源)GameObject(游戏对象)Component(组件) Terrain(地形)Window (窗口) Help( 帮助 )File (文件) ------New Scene 新建场景Open Scene 打开场景Save Scene 保存场景Save Scene as ⋯场景另存为⋯New Project ⋯新建工程文件Open Project ⋯打开工程文件Save Project ⋯保存工程文件Build S ettings ⋯建造设置(这里指建造游戏)Build & Run 建造并运行(这里指建造游戏)Exit 退出Edit (编辑) ------Undo 撤销Redo 重复Cut 剪切Copy 复制Paste 粘贴Duplicate 复制Delete 删除Frame selected 当前镜头移动到所选的物体前Select All 选择全部Preferences 参数选择Play 播放Pause 暂停,中断Step 步骤Load selection 载入所选Save selection 存储所选Project settings 工程设置Render settings 渲染设置Graphics emulation 图形仿真Network emulation 网络仿真Snap settings 对齐设置Assets ( 资源 )-----Reimport 重新导入Create创建Show in Explorer在资源管理器中显示Open打开(打开脚本)Import New Asset...导入新的资源Refresh刷新Import Package...导入资源包Export Package...导出资源包Select Dependencies选择相关Export ogg file导出OGG文件Reimport All重新导入所有Sync VisualStudio Project 同步视觉工作室项目GameObject--------Create Empty 创建一个空的游戏对象(游戏对象)Create Other 创建其他组件Center On Children 子物体归位到父物体中心点Make Parent 创建子父集Clear Parent 取消子父集Apply Changes To Prefab 应用变更为预置Move To View 移动物体到视窗的中心点Align With View 移动物体与视窗对齐Align View to Selected 移动视窗与物体对齐Component( 组件 )---Mesh 网Particles 粒子Physics 物理Audio 音频Rendering 渲染Miscellaneous 杂项Scripts 脚本Camera-Control 摄像机控制Terrain( 地形 )-----Create Terrain 创建地形Import Heightmap - Raw... 导入高度图Export Heightmap - Raw... 导出高度图Set Resolution... 设置分辨率Create Lightmap... 创建光影图Mass Place Trees... 批量种植树Flatten Heightmap... 展平高度图Refresh Tree and Detail Prototypes 刷新树及预置细节Window(窗口 )------Next Window 下个窗口Previous Window 前窗Layouts 布局Scene 场景窗口Game 游戏窗口Inspector Hierarchy Project Animation ProfilerAsset Server Console检视窗口层次窗口工程窗口动画窗口探查窗口资源服务器控制台Help( 帮助 )--------About Unity 关于 UnityEnter serial number Unity Manual Reference Manual Scripting Manual Unity Forum Welcome Screen Release Notes Report a Problem 输入序列号Unity手册参考手册脚本手册Unity论坛欢迎窗口发行说明问题反馈第一章 File (文件)New Scene 新建场景创建一个新的游戏场景Open Scene 打开场景打开一个游戏场景Save Scene保存场景保存一个游戏场景Save Scene as场景另存为游戏场景另存为New Project新建工程文件创建一个新的工程文件Open Project打开工程文件打开一个工程文件Save Project 保存工程文件保存一个工程文件Build Settings建造设置导出游戏的设置Build & Run建造并运行设置并导出游戏Exit退出退出软件这里面我们需要注意的是,创建一个场景与创建一个工程是完全不同的,一个工程文件可以包含多个游戏场景,但场景文件却是唯一的。
Unity中文手册
[Unity 中文手册- Unity 基础] 界面学习界面第一步现在我们开始学习Unity,如果你还没有打开Unity,Macintosh可以双击位于Applications->Unity,Windows双击位于Start->Programs->Unity中的Unity图标来运行它。
第一次运行时你将看到以下场景:Unity运行时缺省的场景,是一个热带天堂的岛屿漫游案例。
Unity 的界面需要花点时间慢慢地去理解和熟悉,主窗口的每一个部分被称为视窗(View ),Unity有多种类型的视窗。
现在让我们逐一了解各个视图。
工程视图(Project View )所有Unity的工程(Project)都是一个资源(Assets )文件夹。
工程视图可查看文件夹里所有内容。
这些内容包含了游戏构成要素(asseat)-场景、脚本、三维建模、纹理、音频文件、Prefabs等。
右击工程视图的特征资源,通过资源管理器可查看文件系统中的实际资源(asset)。
注意:使用OS时绝对不要随意移动asset,任意移动会损坏asset相关的元数据(Metadata),要在工程视图中调整asset。
如果想在工程中添加资源(asset),可将要添加的文件从OS中拖曳并拉到工程视图中或者按这个步骤Assets->Import New Asset进行添加,添加的资源将运用于游戏之中。
关于资源添加更多信息请参考资源工作流程(Asset Workflow)。
场景也是保存在工程视图中。
比如:最早运行Unity时出现是一个默认的岛屿漫游场景,按ctrl-N键可创建新场景,若将当前的场景保存在工程视图中按ctrl-S操作即可。
若想在Unity中创建资源,在控制栏中使用创建下拉列表(Create Drop-down)来创建所需物体,或使用单击右键后->Create来创建资源。
创建下拉别表创建下拉列表中可以打开各种脚本、预设(Prefabs )或构成工程的文件夹。
Unity3D常用脚本PDF.pdf
场景转换:var screenbutton: boolean;function Start(){DontDestroyOnLoad(this);screenbutton = true;}function Update () {if(Input.GetKeyDown(KeyCode.Escape)){screenbutton = true;}}function OnGUI(){if(screenbutton==true)if(GUI.Button(Rect(Screen.width/2-380,Screen.height/2-190,60,50),"Scene1")){ print("You click Scene1");Application.LoadLevel (1);screenbutton = false;}else if(GUI.Button(Rect(Screen.width/2-380,Screen.height/2-130,60,50),"Scene2")){ print("You click Scene2");Application.LoadLevel (2);screenbutton = false;}else if( GUI.Button(Rect(Screen.width/2-375,Screen.height/2-0,50,50),"Quit")){ print("You click Quit");Application.Quit();}}心得:场景转换时,这个程序贴在按钮界面场景中。
在Build Setting(导出)(在File下)菜单中加入所需场景。
0为按钮界面。
可以无限增加场景。
}else if(GUI.Button(Rect(Screen.width/2-380,Screen.height/2-130,60,50),"Scene2")){ print("You click Scene2");Application.LoadLevel (2);screenbutton = false;复制此段程序并做修改。
Unity 3D脚本编程:使用C 语言开发跨平台游戏
13.2.1对DrawCall的优化 13.2.2对物理组件的优化 13.2.3处理内存,却让CPU受伤的GC 13.2.4对代码质量的优化
13.3.1减少绘制的数目 13.3.2优化显存带宽
13.4.1 Unity 3D的内部内存 13.4.2 Mono的托管内存
14.1 Unity 3D脚 本编译流程概览
12.4 AssetBundle 文件的平台兼容性
12.5 AssetBundl e如何识别资
源
12.6本章总 结
12.2.1开发阶段 12.2.2运行阶段
13.1看看 Unity 3D优化
1
需要从哪里着
手
13.2 CPU方面 2
的优化
3 13.3对GPU的
优化
4 13.4内存的优
化
5
13.5本章总结
14.3.1在Unity 3D中使用AOT编译 14.3.2 iOS平台和Full-AOT编译 14.3.3 AOT编译的优势
14.4.1从一个常见的报错说起 14.4.2美丽的JIT 14.4.3模拟JIT的过程 14.4.4 iOS平台的自我保护
14.5.1选择游戏场景和目标平台 14.5.2 Unity 3D发布项目的内部过程 14.5.3 Unity 3D部署到Android平台 14.5.4 Unity 3D部署到iOS平台
7.3定义自 己的定制特 性类
0 5
7.5亲手拓 展Unity 3D的编辑 器
7.1.1 DllImport特性 7.1.2 Serializable特性 7.1.3定制特性到底是谁
8.1初识Unity 3D中 的协程
8.2使用协程实现延 时效果
8.3 Unity 3D协程 背后的秘密——迭代 器
1.3 Unity3dAsset Workflow中文翻译
Asset Workflow(资源工作流程)Here we'll explain the steps to use a single asset with Unity. These steps are general and are meant only as an overview for basic actions. For the example, we'll talk about using a 3D mesh.这里我们讲解Unity的单一资源的使用步骤,这些步骤是通用的且仅作为基本动作的概述,在本例中,我们将讨论如何使用一个三维网格。
Create Rough Asset(创建粗糙资源)Use any supported 3D modeling package to create a rough version of your asset. Our example will use Maya. Work with the asset until you are ready to save. For a list of applications that are supported by Unity, please see this page.使用任何Unity所支持的3D建模软件来创建一个粗制版资源,我们的例子将使用Maya,使用资源工作,直到你准备好保存。
要查看Unity所支持的应用程序列表,请参阅this page。
Import(导入)When you save your asset initially, you should save it normally to the Assets folder in your Project folder. When you open the Unity project, the asset will be detected and imported into the project. When you look in the Project View, you'll see the asset located there, right where you saved it. Please note that Unity uses the FBX exporter provided by your modeling package to convert your models to the FBX file format. You will need to have the FBX exporter of your modeling package available for Unity to use. Alternatively, you can directly export as FBX from your application and save in the Projects folder. For a list of applications that are supported by Unity, please see this page.当你最初保存你的资源时,你应该将它保存到项目文件夹的资源文件夹中,当你打开Unity的项目,资源将被检测并导入项目中,查看项目视图,你会看到保存的资源已经在那里了。
unity3d MonoBehaviour章节中文翻译
MonoBehaviourInherits from Behaviour继承自BehaviourMonoBehaviour is the base class every script derives from.MonoBehaviour是每个脚本的基类.Using Javascript every script automatically derives from MonoBehaviour. When using C# or Boo you have to explicitly derive from MonoBehaviour.每个Javascript脚本自动继承MonoBehaviour.使用C#或Boo时,需要显式继承MonoBehaviour.Note: The checkbox for disabling a MonoBehavior (on the editor) will only prevent Start(), Awake(), Update(), FixedUpdate(), and OnGUI() from executing. If none of these functions are present, the checkbox is not displayed.注意:MonoBehavior对象(编辑器中)的复选框,只有在其有Start(), Awake(), Update(), FixedUpdate(), 和OnGUI()函数时显示,没有这些函数时则隐藏.(另注:译者在PC上Windows平台测试结果与此注释所描述情况不符)See Also: The chapter on scripting in the manual.VariablesuseGUILayout Disabling this lets you skip the GUI layout phase.禁用此项,将会跳过GUILayout部署Functions 函数Invoke Invokes the method methodName in time seconds.根据时间调用指定方法名的方法InvokeRepeating Invokes the method methodName in time seconds.根据时间调用指定方法名的方法CancelInvoke Cancels all Invoke calls on this MonoBehaviour.取消这个MonoBehaviour上的所有调用.IsInvoking Is any invoke on methodName pending?某指定函数是否在等候调用StartCoroutine Starts a coroutine.开始协同程序.StopCoroutine Stops all coroutines named methodName running on this behaviour.停止这个动作中名为methodName的所有协同程序.StopAllCoroutines Stops all coroutines running on this behaviour.停止所有动作的协同程序.Overridable Functions 可重载的函数Update Update is called every frame, if the MonoBehaviour is enabled.当MonoBehaviour启用时,其Update在每一帧被调用LateUpdate LateUpdate is called every frame, if the Behaviour is enabled.当MonoBehaviour启用时,其LateUpdate在每一帧被调用FixedUpdate This function is called every fixed framerate frame, if the MonoBehaviour is enabled.当MonoBehaviour启用时,其FixedUpdate在每一帧被调用Awake Awake is called when the script instance is being loaded.当一个脚本实例被载入时Awake被调用.Start Start is called just before any of the Update methods is called the first time.Start在Update调用前被调用.Reset Reset to default values.重置,恢复到默认值.OnMouseEnter OnMouseEnter is called when the mouse entered the GUIElement or Collider.当鼠标进入到GUIElement(GUI组件)或Collider(碰撞体)中时调用OnMouseEnter.OnMouseOver OnMouseOver is called every frame while the mouse is over the GUIElement or Collider.当鼠标悬浮在GUIElement(GUI组件)或Collider(碰撞体)上时调用OnMouseOver.OnMouseExit OnMouseExit is called when the mouse is not any longer over the GUIElement or Collider.当鼠标移出GUIElement(GUI组件)或Collider(碰撞体)上时调用OnMouseExitOnMouseDown OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collid当用户在GUIElement(GUI组件)或Collider(碰撞体)上点击鼠标时调用OnMouseDownOnMouseUp OnMouseUp is called when the user has released the mouse button.用户释放鼠标键的时候调用这个.OnMouseDrag OnMouseDrag is called when the user has clicked on a GUIElement or Collider and is still holding down thmouse.当用户鼠标拖拽GUIElement(GUI组件)或Collider(碰撞体)时调用OnMouseDragOnTriggerEnter OnTriggerEnter is called when the Collider other enters the trigger.当Collider(碰撞体)进入trigger(触发器)时调用OnTriggerEnter.OnTriggerExit OnTriggerExit is called when the Collider other has stopped touching the trigger.当Collider(碰撞体)移出trigger(触发器)时调用OnTriggerExit.OnTriggerStay OnTriggerStay is called once per frame for every Collider other that is touching the trigger.当Collider(碰撞体)触发trigger(触发器)时在每一帧调用OnTriggerStay.OnCollisionEnter OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider.当此collider/rigidbody触发另一个rigidbody/collider时,OnCollisionEnter将被调用.OnCollisionExit OnCollisionExit is called when this collider/rigidbody has stopped touching another rigidbody/collider.当此collider/rigidbody停止触发另一个rigidbody/collider时,OnCollisionExit将被调用. OnCollisionStay OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider.当此collider/rigidbody触发另一个rigidbody/collider时,OnCollisionStay将会在每一帧被调用. OnControllerColliderHit OnControllerColliderHit is called when the controller hits a collider while performing a Move.当controller碰撞到collider时OnControllerHit被调用.OnJointBreak Called when a joint attached to the same game object broke.当附在同一对象上的关节被断开时调用.OnParticleCollision OnParticleCollision is called when a particle hits a collider.当粒子碰到collider时被调用.OnBecameVisible OnBecameVisible is called when the renderer became visible by any camera.当renderer(渲染器)在任何相机上可见时调用OnBecameVisible.OnBecameInvisible OnBecameInvisible is called when the renderer is no longer visible by any camera.当renderer(渲染器)在任何相机上都不可见时调用OnBecameInvisible.OnLevelWasLoaded This function is called after a new level was loaded.当一个新关卡被载入时此函数被调用.OnEnable This function is called when the object becomes enabled and active.当对象变为可用或激活状态时此函数被调用.OnDisable This function is called when the behaviour becomes disabled () or inactive.当对象变为不可用或非激活状态时此函数被调用.OnPreCull OnPreCull is called before a camera culls the scene.在相机剪裁场景之前被调用.OnPreRender OnPreRender is called before a camera starts rendering the scene.在相机渲染场景之前被调用.OnPostRender OnPostRender is called after a camera finished rendering the scene.在相机完成场景渲染之后被调用.OnRenderObject OnRenderObject is called after camera has rendered the scene.在相机场景渲染完成后被调用OnWillRenderObject OnWillRenderObject is called once for each camera if the object is visible.如果对象可见每个相机都会调用它.OnGUI OnGUI is called for rendering and handling GUI events.渲染和处理GUI事件时调用.OnRenderImage OnRenderImage is called after all rendering is complete to render image当完成所有渲染后被调用,用来渲染图片后期效果.OnDrawGizmosSelected Implement this OnDrawGizmosSelected if you want to draw gizmos only if the object is selected.如果你想在物体被选中时绘制gizmos,去实现这个函数.OnDrawGizmos Implement this OnDrawGizmos if you want to draw gizmos that are also pickable and always drawn.如果你想绘制可被点选的gizmos,去实现这个.OnApplicationPause Sent to all game objects when the player pauses.当玩家暂停时发送到所有的游戏物体.OnApplicationFocus Sent to all game objects when the player gets or looses focus.当玩家获取或失去焦点时发送给所有游戏物体.OnApplicationQuit Sent to all game objects before the application is quit.在应用退出之前发送给所有的游戏物体.OnPlayerConnected Called on the server whenever a new player has successfully connected.当一个新玩家成功连接时在服务器上被调用.OnServerInitialized Called on the server whenever a Network.InitializeServer was invoked and has completed.当Network.InitializeServer被调用并完成时,在服务器上调用这个函数OnConnectedToServer Called on the client when you have successfully connected to a server当你成功连接到服务器时,在客户端被调用.OnPlayerDisconnected Called on the server whenever a player disconnected from the server.当一个玩家从服务器上断开时在服务器端调用.OnDisconnectedFromServer Called on the client when the connection was lost or you disconnected from the server.当失去连接或从服务器端断开时在客户端调用.OnFailedToConnect Called on the client when a connection attempt fails for some reason.当一个连接因为某些原因失败时在客户端调用.OnFailedToConnectToMasterServer Called on clients or servers when there is a problem connecting to the MasterServer.当连接主服务器出现问题时在客户端或服务器端调用.OnMasterServerEvent Called on clients or servers when reporting events from the MasterServer.当报告事件来自主服务器时在客户端或服务器端调用.OnNetworkInstantiate Called on objects which have been network instantiated with Network.Instantiate当一个物体使用Network.Instantiate进行网络初始化时调用. OnSerializeNetworkView Used to customize synchronization of variables in a script watched by a network view.在一个网络视图脚本中,用于自定义变量同步Class Functions 类函数print Logs message to the Unity Console. This function is identical to Debug.Log.记录消息到Unity控制台.这个函数和Debug.Log作用相同.Inherited members 被继承的成员Inherited Variables 被继承的变量enabled Enabled Behaviours are Updated, disabled Behaviours are not.启用时Behaviours会执行更新,反之不更新.transform The Transform attached to this GameObject (null if there is none attached).附加在本游戏对象上的Transform(没有则为null).rigidbody The Rigidbody attached to this GameObject (null if there is none attached).附加在本游戏对象上的Rigidbody(没有则为null).camera The Camera attached to this GameObject (null if there is none attached).附加在本游戏对象上的Camera(没有则为null).light The Light attached to this GameObject (null if there is none attached).附加在本游戏对象上的Light (没有则为null).animation The Animation attached to this GameObject (null if there is none attached).附加在本游戏对象上的animation (没有则为null).constantForce The ConstantForce attached to this GameObject (null if there is none attached).附加在本游戏对象上的ConstantForce(没有则为null).renderer The Renderer attached to this GameObject (null if there is none attached).附加在本游戏对象上的Renderer(没有则为null).audio The AudioSource attached to this GameObject (null if there is none attached).附加在本游戏对象上的AudioSource(没有则为null).guiText The GUIText attached to this GameObject (null if there is none attached).附加在本游戏对象上的GUIText(没有则为null).networkView The NetworkView attached to this GameObject (Read Only). (null if there is none attached)附加在本游戏对象上的NetworkView(只读)(没有则为null).guiTexture The GUITexture attached to this GameObject (Read Only). (null if there is none attached)附加在本游戏对象上的GUITexture(只读) (没有则为null).collider The Collider attached to this GameObject (null if there is none attached).附加在本游戏对象上的Collider(没有则为null).hingeJoint The HingeJoint attached to this GameObject (null if there is none attached).附加在本游戏对象上的HingeJoint(没有则为null).particleEmitter The ParticleEmitter attached to this GameObject (null if there is none attached).附加在本游戏对象上的ParticleEmitter(没有则为null).gameObject The game object this component is attached to. A component is always attached to a game object.该组件附加的游戏对象.组件总是附加在一个游戏对象上.tag The tag of this game object.该游戏对象的标签.name The name of the object.该游戏对象的名字.hideFlags Should the object be hidden, saved with the scene or modifiable by the user?设置是否隐藏,保存在场景中或被用户修改.Inherited Functions 被继承的函数GetComponent Returns the component of Type type if the game object has one attached, null if it doesn't.返回游戏对象上某类型的组件.没有则返回null.GetComponentInChildren Returns the component of Type type in the GameObject or any of its children using depth first search.返回游戏对象或其子物体上某类型的组件.没有则返回null.搜素时深度优先.GetComponentsInChildren Returns all components of Type type in the GameObject or any of its children.返回游戏对象或其子物体上所有某类型的组件GetComponents Returns all components of Type type in the GameObject.返回游戏对象上某类型的所有组件.CompareTag Is this game object tagged tag?核对游戏对象的标签SendMessageUpwards Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the Behaviour在该游戏对象的所有MonoBehaviour上及其父物体上调用名为methodName的方法,SendMessage Calls the method named methodName on every MonoBehaviour in this game object.在该游戏对象的所有MonoBehaviour上调用名为methodName的方法,BroadcastMessage Calls the method named methodName on every MonoBehaviour in this game object or any of its children.在该游戏对象的所有MonoBehaviour上及其子物体上调用名为methodName的方法,GetInstanceID Returns the instance id of the object.返回该物体的实例ID.Inherited Class Functions 被继承的类函数operator bool Does the object exist?判断物体是否存在.Instantiate Clones the object original and returns the clone.复制一个物体并返回该备份.Destroy Removes a gameobject, component or asset.移除一个物体,组件或资源.DestroyImmediate Destroys the object obj immediately. It is strongly recommended to use Destroy instead.立刻销毁一个物体.建议用Destroy代替之.FindObjectsOfType Returns a list of all active loaded objects of Type type.返回找到的所有指定类型的对象.FindObjectOfType Returns the first active loaded object of Type type.返回找到的指定类型的第一个对象operator ==Compares if two objects refer to the same比较两个物体是否相同.operator !=Compares if two objects refer to a different object比较两个物体是否不同.DontDestroyOnLoad Makes the object target not be destroyed automatically when loading a new scene.确保目标对象在加载新场景时不被自动销毁.eGUILayoutDescriptionDisabling this lets you skip the GUI layout phase.禁用此项,将会跳过GUILayout部署阶段It can only be used if you do not use GUI.Window and GUILayout inside of this OnGUI call.它只用于在假如你不用GUI.Window和GUILayout的时候.MonoBehaviour.Invokefunction Invoke (methodName : string, time : float) : voidDescriptionInvokes the method methodName in time seconds.根据时间调用指定方法名的方法.JavaScript// Launches a projectile in 2 seconds// 2秒后发射炮弹var projectile : Rigidbody;Invoke("LaunchProjectile", 2);function LaunchProjectile () {var instance : Rigidbody = Instantiate(projectile);instance.velocity = Random.insideUnitSphere * 5;}MonoBehaviour.InvokeRepeatingfunction InvokeRepeating (methodName : string, time : float, repeatRate : float) : voidDescriptionInvokes the method methodName in time seconds.根据时间调用指定方法名的方法After the first invocation repeats calling that function every repeatRate seconds. 从第一次调用开始,每隔repeatRate时间调用一次.JavaScript// Starting in 2 seconds.// a projectile will be launched every 0.3 seconds// 2秒后开始// 每0.3秒发射一颗炮弹var projectile : Rigidbody;InvokeRepeating("LaunchProjectile", 2, 0.3);function LaunchProjectile () {var instance : Rigidbody = Instantiate(projectile);instance.velocity = Random.insideUnitSphere * 5;}MonoBehaviour.CancelInvokefunction CancelInvoke () : voidDescriptionCancels all Invoke calls on this MonoBehaviour.取消这个MonoBehaviour上的所有调用.JavaScript// Starting in 2 seconds.// a projectile will be launched every 0.3 seconds// 2秒后开始// 每0.3秒发射一颗炮弹var projectile : Rigidbody;InvokeRepeating("LaunchProjectile", 2, 0.3);// Cancels the repeating invoke call,// when the user pressed the ctrl button// 当用户按下ctrl键取消repeating调用function Update() {if (Input.GetButton ("Fire1"))CancelInvoke();}function LaunchProjectile () {instance = Instantiate(projectile);instance.velocity = Random.insideUnitSphere * 5;}function CancelInvoke (methodName : string) : voidDescriptionCancels all Invoke calls with name methodName on this behaviour.取消所有名为methodName的调用.JavaScript// Starting in 2 seconds.// a projectile will be launched every 0.3 seconds// 2秒后开始// 每0.3秒发射一颗炮弹var projectile : Rigidbody;InvokeRepeating("LaunchProjectile", 2, 0.3);// Cancels the repeating invoke call,// when the user pressed the ctrl button// 当用户按下ctrl键取消repeating调用function Update() {if (Input.GetButton ("Fire1"))CancelInvoke("LaunchProjectile");}function LaunchProjectile () {instance = Instantiate(projectile);instance.velocity = Random.insideUnitSphere * 5;}MonoBehaviour.IsInvokingDescriptionIs any invoke on methodName pending?某指定函数是否在等候调用.JavaScript// Instantiates a project after 2 seconds when Space key was pressed// and it will only call the function after the function has ended its execution // 按下空格键2秒后实例化一个炮弹,在该函数执行完毕之前仅调用此函数var projectile : Rigidbody;function Update() {if(Input.GetKeyDown(KeyCode.Space) && !IsInvoking("LaunchProjectile"))Invoke("LaunchProjectile", 2);}function LaunchProjectile () {var instance : Rigidbody = Instantiate(projectile);instance.velocity = Random.insideUnitSphere * 5;}function IsInvoking () : boolDescriptionIs any invoke pending on this MonoBehaviour?此MonoBehaviour上是否有调用在等候.MonoBehaviour.StartCoroutinefunction StartCoroutine (routine : IEnumerator) : CoroutineDescriptionStarts a coroutine.开始协同程序.The execution of a coroutine can be paused at any point using the yield statement. The yield return value specifies when the coroutine is resumed. Coroutines are excellent when modelling behaviour over several frames. Coroutines have virtually no performance overhead. StartCoroutine function always returns immediately, however you can yield the result. This will wait until the coroutine has finished execution.一个协同程序在执行过程中,可以在任意位置使用yield语句.yield的返回值控制何时恢复协同程序向下执行.协同程序在对象自有帧执行过程中堪称优秀.协同程序在性能上没有更多的开销.StartCoroutine函数是立刻返回的,但是yield可以延迟结果.直到协同程序执行完毕.When using JavaScript it is not necessary to use StartCoroutine, the compiler will do this for you. When writing C# code you must call StartCoroutine.用javascript不需要添加StartCoroutine,编译器将会替你完成.但是在C#下,你必须调用StartCoroutine.JavaScript// In this example we show how to invoke a coroutine and continue executing// the function in parallel.// 此例演示如何调用协同程序和它的执行function Start() {// - After 0 seconds, prints "Starting 0.0"// - After 0 seconds, prints "Before WaitAndPrint Finishes 0.0"// - After 2 seconds, prints "WaitAndPrint 2.0"// 先打印"Starting 0.0"和"Before WaitAndPrint Finishes 0.0"两句,2秒后打印"WaitAndPrint 2.0"print ("Starting " + Time.time);// Start function WaitAndPrint as a coroutine. And continue execution while it is running // this is the same as WaintAndPrint(2.0) as the compiler does it for you automatically // 协同程序WaitAndPrint在Start函数内执行,可以视同于它与Start函数同步执行.StartCoroutine(WaitAndPrint(2.0));print ("Before WaitAndPrint Finishes " + Time.time);}function WaitAndPrint (waitTime : float) {// suspend execution for waitTime seconds// 暂停执行waitTime秒yield WaitForSeconds (waitTime);print ("WaitAndPrint "+ Time.time);}Another Example:JavaScript// In this example we show how to invoke a coroutine and wait until it// is completed// 在这个例子中我们演示如何调用协同程序并直到它执行完成.function Start() {// - After 0 seconds, prints "Starting 0.0"// - After 2 seconds, prints "WaitAndPrint 2.0"// - After 2 seconds, prints "Done 2.0"// 0秒时打印"Starting 0.0",2秒后打印"WaitAndPrint 2.0"和"Done 2.0"print ("Starting " + Time.time);// Start function WaitAndPrint as a coroutine. And wait until it is completed.// the same as yield WaitAndPrint(2.0);// 运行WaitAndPrint直到完成yield StartCoroutine(WaitAndPrint(2.0));print ("Done " + Time.time);}function WaitAndPrint (waitTime : float) {// suspend execution for waitTime seconds// 等待waitTime秒yield WaitForSeconds (waitTime);print ("WaitAndPrint "+ Time.time);}function StartCoroutine (methodName : string, value : object = null) : CoroutineDescriptionStarts a coroutine named methodName.开始一个叫methodName的协同程序.In most cases you want to use the StartCoroutine variation above. However StartCoroutine using a string method name allows you to use StopCoroutine with a specific method name. The downside is that the string version has a higher runtime overhead to start the coroutine and you can pass only one parameter很多情况下,我们会用到StartCoroutine的一个变体.使用有字符串方法名的StartCoroutine允许你用StopCoroutine去停止它.其缺点就是会有较高的性能开销,而且你只能传递一个参数.JavaScript// In this example we show how to invoke a coroutine using a string name and stop it// 这个例子演示如何调用一个使用字符串名称的协同程序并停掉它function Start () {StartCoroutine("DoSomething", 2.0);yield WaitForSeconds(1);StopCoroutine("DoSomething");}function DoSomething (someParameter : float) {while (true) {print("DoSomething Loop");// Yield execution of this coroutine and return to the main loop until next frame// 停止协同程序的执行并返回到主循环直到下一帧.yield;}}MonoBehaviour.StopCoroutinefunction StopCoroutine (methodName : string) : voidDescriptionStops all coroutines named methodName running on this behaviour.停止这个动作中名为methodName的所有协同程序.Please note that only StartCoroutine using a string method name can be stopped using StopCoroutine.请注意只有StartCoroutine使用一个字符串方法名时才能用StopCoroutine停用之.JavaScript// In this example we show how to invoke a coroutine using a string name and stop it// 这个例子演示如何调用一个使用字符串名称的协同程序并停掉它function Start () {StartCoroutine("DoSomething", 2.0);yield WaitForSeconds(1);StopCoroutine("DoSomething");}function DoSomething (someParameter : float) {while (true) {print("DoSomething Loop");// Yield execution of this coroutine and return to the main loop until next frame // 停止协同程序的执行并返回到主循环直到下一帧.yield;}}MonoBehaviour.StopAllCoroutinesfunction StopAllCoroutines () : voidDescriptionStops all coroutines running on this behaviour.停止所有动作的协同程序.JavaScript// Starts the coroutine// 开始协同程序.StartCoroutine ("DoSomething");// Cancels the coroutine immediately afterwards// 随后立即取消之.function DoSomething () {while (true) {yield;}}StopAllCoroutines();MonoBehaviour.Updatefunction Update () : voidDescriptionUpdate is called every frame, if the MonoBehaviour is enabled.当MonoBehaviour启用时,其Update在每一帧被调用Update is the most commonly used function to implement any kind of game behaviour.Update是实现各种游戏行为最常用的函数.JavaScript// Moves the object forward 1 meter a second// 以每秒1米的速度向前移动物体function Update () {transform.Translate(0, 0, Time.deltaTime * 1);}In order to get the elapsed time since last call to Update, use Time.deltaTime. This function is only called if the Behaviour is enabled. Override this function in order to provide your component's functionality.为了获取自最后一次调用Update所用的时间,可以用Time.deltaTime.这个函数只有在Behaviour启用时被调用.实现组件功能时重载这个函数.teUpdatefunction LateUpdate () : voidDescriptionLateUpdate is called every frame, if the Behaviour is enabled.当MonoBehaviour启用时,其LateUpdate在每一帧被调用LateUpdate is called after all Update functions have been called. This is useful to order script execution. For example a follow camera should always be implemented in LateUpdate because it tracks objects that might have moved inside Update.LateUpdate是在所有Update函数调用后被调用.这可用于调整脚本执行顺序.例如:当物体在Update里移动时,跟随物体的相机可以在LateUpdate里实现,JavaScript// Moves the object forward 1 meter a second// 以每秒1米的速度向前移动物体function LateUpdate () {transform.Translate(0, 0, Time.deltaTime * 1);}In order to get the elapsed time since last call to LateUpdate, use Time.deltaTime. This function is only called if the Behaviour is enabled. Override this function in order to provide your component's functionality.为了获取自最后一次调用LateUpdate所用的时间,可以用Time.deltaTime.这个函数只有在Behaviour启用时被调用.实现组件功能时重载这个函数.MonoBehaviour.FixedUpdatefunction FixedUpdate () : voidDescriptionThis function is called every fixed framerate frame, if the MonoBehaviour is enabled.当MonoBehaviour启用时,其FixedUpdate在每一帧被调用.FixedUpdate should be used instead of Update when dealing with Rigidbody. For example when adding a force to a rigidbody, you have to apply the force every fixed frame inside FixedUpdate instead of every frame inside Update.处理Rigidbody时,需要用FixedUpdate代替Update.例如:给刚体加一个作用力时,你必须应用作用力在FixedUpdate里的固定帧,而不是Update中的帧.(两者帧长不同)JavaScript// Apply a upwards force to the rigid body every frame// 每帧应用一个向上的力到刚体上function FixedUpdate () {rigidbody.AddForce (Vector3.up);}In order to get the elapsed time since last call to FixedUpdate, use Time.deltaTime This function is only called if the Behaviour is enabled. Override this function in order to provide your component's functionality.为了获取自最后一次调用FixedUpdate所用的时间,可以用Time.deltaTime.这个函数只有在Behaviour启用时被调用.实现组件功能时重载这个函数.MonoBehaviour.Awakefunction Awake () : voidDescriptionAwake is called when the script instance is being loaded.当一个脚本实例被载入时Awake被调用.Awake is used to initialize any variables or game state before the game starts. Awake is called only once during the lifetime of the script instance. Awake is called after all objects are initialized so you can safely speak to other objects or query them using eg. GameObject.FindWithTag. Each GameObject's Awake is called in a random order between objects. Because of this, you should use Awake to set up references between scripts, and use Start to pass any information back and forth. Awake is always called before any Start functions. This allows you to order initialization of scripts. Awake can not act as a coroutine.Awake用于在游戏开始之前初始化变量或游戏状态.在脚本整个生命周期内它仅被调用一次.Awake在所有对象被初始化之后调用,所以你可以安全的与其他对象对话或用诸如GameObject.FindWithTag这样的函数搜索它们.每个游戏物体上的Awke以随机的顺序被调用.因此,你应该用Awake来设置脚本间的引用,并用Start来传递信息Awake总是在Start之前被调用.它不能用来执行协同程序.Note for C# and Boo users: use Awake instead of the constructor for initialization, as the serialized state of the component is undefined at construction time. Awake is called once, just like the constructor.C#和Boo用户注意:Awake不同于构造函数,物体被构造时并没有定义组件的序列化状态.Awake像构造函数一样只被调用一次.JavaScriptprivate var target : GameObject;function Awake () {target = GameObject.FindWithTag ("Player");}Awake cannot be a co-routine.Awake不能用作协同程序.MonoBehaviour.Startfunction Start () : voidDescriptionStart is called just before any of the Update methods is called the first time.Start仅在Update函数第一次被调用前调用Start is only called once in the lifetime of the behaviour. The difference between Awake and Start is that Start is only called if the script instance is enabled. This allows you to delay any initialization code, until it is really needed. Awake is always called before any Start functions. This allows you to order initialization of scripts.Start在behaviour的生命周期中只被调用一次.它和Awake的不同是Start只在脚本实例被启用时调用.你可以按需调整延迟初始化代码.Awake总是在Start之前执行.这允许你协调初始化顺序.The Start function is called after all Awake functions on all script instances have been called.在所有脚本实例中,Start函数总是在Awake函数之后调用.JavaScript// Initializes the target variable.// target is private and thus not editable in the inspector// 初始化目标变量// 目标是私有的并且不能在检视面板中编辑private var target : GameObject;function Start () {target = GameObject.FindWithTag ("Player");}MonoBehaviour.Resetfunction Reset () : voidDescriptionReset to default values.重置为默认值Reset is called when the user hits the Reset button in the Inspector's context menu or when adding the component the first time. This function is only called in editor mode. Reset is most commonly used to give good default values in the inspector.Reset是在用户点击检视面板的Reset按钮或者首次添加该组件时被调用.此函数只在编辑模式下被调用.Reset最常用于在检视面板中给定一个最常用的默认值.JavaScript// Sets target to a default value.// This could be used in a follow camera.// 设置target为默认值// 这可以用于一个跟踪相机var target : GameObject;function Reset () {// Only set target if it is not assigned yet.// 如果target没有赋值,设置它if (!target)target = GameObject.FindWithTag ("Player");}MonoBehaviour.OnMouseEnterfunction OnMouseEnter () : voidDescriptionOnMouseEnter is called when the mouse entered the GUIElement or Collider.当鼠标进入到GUIElement(GUI组件)或Collider(碰撞体)中时调用OnMouseEnter.JavaScript// Attach this script to a mesh to make// it red when the mouse is over the mesh// 附加这个脚本到网格// 当鼠标经过网格时网格变红色function OnMouseEnter () {renderer.material.color = Color.red;}This function is not called on objects that belong to Ignore Raycast layer.OnMouseEnter can be a co-routine, simply use the yield statement in the function. This event is sent to all scripts attached to the Collider or GUIElement.这个函数不会在属于Ignore Raycast的层上调用.它可以被作为协同程序,在函数体内使用yield语句.这个事件将发送到所有附在Collider或GUIElement的脚本上.IMPORTANT: This function has no effect on iPhone.注意:这个函数在Iphone上无效.MonoBehaviour.OnMouseOverfunction OnMouseOver () : voidDescriptionOnMouseOver is called every frame while the mouse is over the GUIElement or Collider.当鼠标悬浮在GUIElement(GUI组件)或Collider(碰撞体)上时调用OnMouseOver.JavaScript// Fades the red component of the material to zero// while the mouse is over the mesh// 当鼠标在网格上时渐变红色组件为0function OnMouseOver () {renderer.material.color -= Color(0.1, 0, 0) * Time.deltaTime;}This function is not called on objects that belong to Ignore Raycast layer.OnMouseOver can be a co-routine, simply use the yield statement in the function. This event is sent to all scripts attached to the Collider or GUIElement.这个函数不会在属于Ignore Raycast的层上调用.它可以被作为协同程序,在函数体内使用yield语句.这个事件将发送到所有附在Collider或GUIElement的脚本上.IMPORTANT: This function has no effect on iPhone.注意:此函数在iPhone上无效.MonoBehaviour.OnMouseExitfunction OnMouseExit () : voidDescriptionOnMouseExit is called when the mouse is not any longer over the GUIElement or Collider.当鼠标移出GUIElement(GUI组件)或Collider(碰撞体)上时调用OnMouseExit.OnMouseExit balances out OnMouseEnterOnMouseExit与OnMouseEnter相反.JavaScript。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Unity3D脚本中文教程 Part1 一、脚本概览这是一个关于Unity内部脚本如何工作的简单概览。
Unity内部的脚本是通过附加自定义脚本对象到游戏物体组成的。
在脚本对象内部不同志的函数被特定的事件调用。
最常用的列在下面Update 这个函数在渲染一帧之前被调用这里是大部分游戏行为代码被执行的地方除了物理代码。
FixedUpdate 这个函数在每个物理时间步被调用一次这是处理基于物理游戏的地方。
在任何函数之外的代码在任何函数之外的代码在物体被加载的时候运行这个可以用来初始化脚本状态。
注意文档的这个部份假设你是用Javascript参考用C编写获取如何使用C和Boo编写脚本的信息。
你也能定义事件句柄它们的名称都以On开始例如OnCollisionEnter为了查看完整的预定义事件的列表参考MonoBehaviour 文档。
概览常用操作大多数游戏物体的操作是通过游戏物体的Transform或Rigidbody来做的在行为脚本内部它们可以分别通过transform和rigidbody访问因此如果你想绕着Y轴每帧旋转5度你可以如下写function Update transform.Rotate050 如果你想向前移动一个物体你应该如下写function Update transform.Translate002 概览跟踪时间Time类包含了一个非常重要的类变量称为deltaTime这个变量包含从上一次调用Update或FixedUpdate根据你是在Update函数还是在FixedUpdate函数中到现在的时间量。
所以对于上面的例子修改它使这个物体以一个恒定的速度旋转而不依赖于帧率function Update transform.Rotate05Time.deltaTime0 移动物体function Update transform. Translate 0 02Time.deltaTime 如果你加或是减一个每帧改变的值你应该将它与Time.deltaTime 相乘。
当你乘以Time.deltaTime时你实际的表达我想以10米/秒移动这个物体不是10米/帧。
这不仅仅是因为你的游戏将独立于帧而运行同时也是因为运动的单位容易理解。
米/秒另一个例子如果你想随着时间增加光照的范围。
下面的表达式以2单位/秒改变半径。
function Update light.range 2.0 Time.deltaTime 当通过力处理刚体的时候你通常不必用Time.deltaTime因为引擎已经为你考虑到了这一点。
概览访问其他组件组件被附加到游戏物体附加Renderer到游戏物体使它在场景中渲染附加一个Camera使它变为相机物体所有的脚本都是组件因为它们能被附加到游戏物体。
最常用的组件可以作为简单成员变量访问Component 可如下访问Transform transform Rigidbody rigidbody Renderer renderer Camera camera only on camera objects Light light only on light objects Animation animation Collider collider …等等。
对于完整的预定义成员变量的列表。
查看ComponentBehaviour和MonnoBehaviour类文档。
如果游戏物体没有你想取的相同类型的组件上面的变量将被设置为null。
任何附加到一个游戏物体的组件或脚本都可以通过GetComponent访问。
transform.Translate030 //等同于GetComponentTransform.Translate0 1 0 注意transfom和Transform之间大小写的区别前者是变量小写后者是类或脚本名称大写。
大小写不同使你能够从类和脚本名中区分变量。
应用我们所学你可以使用GetComponent找到任何附加在同一游戏物体上的脚本和组件请注意要使用下面的例子能够工作你需要有一个名为OtherScript的脚本其中包含一个DoSomething函数。
OtherScript脚本必须与下面的脚本附加到相同的物体上。
//这个在同一游戏物体桑找到名为OtherScript的脚本//并调用它上加的DoSomething function Update otherScript GetComponentOtherScriptotherScript.DoSomething 概览访问其它游戏物体大多数高级的代码不仅需要操作一个物体Unity脚本接口有各种方法来找到并访问其他游戏物体和组件。
在下面我们假定有个一名为OtherScriptjs的脚本附加到场景的游戏物体上。
var foo 5 function DoSomething param : String printparam quot with foo: quot foo 1.通过检视面板赋值引用你可以通过检视面板赋值变量到任何物体//变换拖动到target的物体var target : Transform function Update target.Translate0 1 0 你也可以在检视面板中公开到其他物体的引用下面你可以拖动一个包含的游戏物体到检视面板中的target槽。
//设置在检视面板中赋值的target变量上的foo调用DoSomething var target :OtherScript function Update //设置target物体的foo变量target.foo 2 // 调用target上的DoSomethingtarget.DoSomethingquotHelloquot 2.通过物体层次定位对于一个已经存在的物体可以通过游戏物体的Transform组件来找到子和父物体//找到脚本所附加的//游戏物体的子―Hand‖transform.FindquotHandquot.Translate0 1 0 一旦在层次视图中找到这个变换你可以使用GetComponent来获取其他脚本//找到名为―Hand‖的子//在附加到它上面的OtherScript中设置foo为2transform.FindquotHandquot.Translate0 1 0 //找到名为―Hand‖的子//然后应用一个力到附加在hand上的刚体transform.FindquotHandquot.GetComponentOtherScript.DoSo methingquotHelloquot // 找到名为―Hand‖的了// 然后应用一个力到附加在hand上的刚体transform.FindquotHandquot.rigidbody.AddForce0 10 0 你可以循环所有的子//变换的所有子向上移动10个单位for var child : Transform in transform child.Translate0 1 0 参考Transform类文档获取更多信息。
Part 2 3.根据名称或标签定位. 你可以使用GameObject.FindWithTag和GameObject.FindGameObjectsWithTag搜索具有特定标签的游戏物体使用GameObject.Find根据名称查找物体。
function Start // 按照名称var go GameObject.FindquotSomeGuyquotgo.transform.Translate0 1 0 // 按照标签var player GameObject.FindWithTagquotPlayerquotplayer.transform.Translate0 1 0 你可以在结果上使用GetComponent在找到的游戏物体上得到任何脚本或组件。
function Start // 按名称var goGameObject.FindquotSomeGuyquotgo.GetComponentOtherScript.DoSomething // 按标签var player GameObject.FindWithTagquotPlayerquotplayer.GetComponentOtherScript.DoSomething 一些特殊的物体有快捷方式如主相机使用Camera.main。
4.作为参数传递一些事件消息在事件包含详细信息。
例如触发器事件传递碰撞物体的Collider组件到处理函数。
OnTriggerStay给我们一个到碰撞器的引用。
从这个碰撞器我们可以获取附加到其上的刚体。
function OnTriggerStay other : Collider // 如果另一个碰撞器也有一个刚体// 应用一个力到它上面if other.rigidbody other.rigidbody.AddForce0 2 0 或者我们可以通过碰撞器获取附加在同一个物体上的任何组件。
function OnTriggerStay other : Collider // 如果另一个碰撞器附加了OtherScript // 调用它上面的DoSomething // 大多数时候碰撞器不会附加脚本// 所以我们需要首先检查以避免null引用异常if other.GetComponentOtherScriptother.GetComponentOtherScript.DoSomething 注意通过上述例子中的other变量你可以访问碰撞物体中的任何组件。
5.一种类型的所有脚本使用Object.FindObjectsOfType找到所有具有相同类或脚本名称的物体或者使用Object.FindObjectOfType.找到这个类型的第一个物体。
function Start // 找到场景中附加了OtherScript的任意一个游戏物体var other : OtherScript FindObjectOfTypeOtherScript other.DoSomething 概览向量Unity使用Vector3类同一表示全体3D向量3D向量的不同组件可以通过想xy和z成员变量访问。
var aPosition : Vector3 aPosition.x 1 aPosition.y 1 aPosition.z 1 你也能够使用Vector3构造函数来同时初始化所有组件。
var aPosition Vector31 1 1 Vector3也定义了一些常用的变量值。
var direction Vector3.up // 与Vector30 1 0相同单个向量上的操作可以使用下面的方式访问someVector.Normalize 使用多个向量的操作可以使用Vector3类的数theDistance Vector3.DistanceoneVector otherVector 注意你必须在函数名之前写Vector3来告诉JavaScript在哪里找到这个函数这适用于所有类函数你也可以使用普通数学操作来操纵向量。