Unity3D脚本--常用代码集

这篇博客介绍了Unity3D中实现物体交互的多种方法,包括碰撞检测、光线投射、触发器和声音播放。详细讲解了ControllerColliderHit、RaycastHit、OnTriggerEnter和OnCollisionEnter等组件的使用,以及如何播放不同类型的音频。此外,还涵盖了销毁物体、给刚体加速度、忽略碰撞、协同程序、动态添加删除脚本、粒子系统、for循环和数组、延时函数、场景加载以及菜单创建等内容。
摘要由CSDN通过智能技术生成

首先给大家分享一个巨牛巨牛的人工智能教程,是我无意中发现的。教程不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵段子,像看小说一样,哈哈~我正在学习中,觉得太牛了,所以分享给大家!点这里可以跳转到教程

               

1. 访问其它物体

1) 使用Find()和FindWithTag()命令
Find和FindWithTag是非常耗费时间的命令,要避免在Update()中和每一帧都被调用的函数中使用。在Start()和Awake()中使用,使用公有变量把它保存下来,以供后面使用。如:
  公有变量= GameObject.Find("物体名"); 或
  公有变量= GameObject.FindWithTag("物体标签名");
2) 把一个物体拖到公有变量上
3) 引用脚本所在的物体的组件上的参数,如下所示:

   transform.position = Vector3(0,5,4);   renderer.material.color = Color.blue;   light.intensity = 8;

4) SendMessge()命令:一个调用其它物体上指令(即物体上的脚本中的函数)的方法

5) GetComponent()命令:引用一个组件

实例代码如下所示:

#pragma strictvar thelight:GameObject;var thetxt:GameObject;var theCube1:GameObject;function Start () { thelight = GameObject.Find("Spotlight"); thetxt = GameObject.FindWithTag("txt"); theCube1 = GameObject.Find("Cube1");}function Update () { if(Input.GetKey(KeyCode.L)){  thelight.light.intensity += 0.01;  thetxt.GetComponent(GUIText).text = "当前亮度:"+thelight.light.intensity; }  if(Input.GetKey(KeyCode.K)){  thelight.light.intensity -= 0.01;  thetxt.GetComponent(GUIText).text = "当前亮度:"+thelight.light.intensity; } if(Input.GetKey(KeyCode.S)){  theCube1.SendMessage("OnMouseDown"); //调用theCube1所有脚本中的OnMouseDown函数 }}

2. 制作第一人称控制器

    第一人称控制器脚本代码如下所示:

#pragma strictvar speed:float=6.0;var jumpspeed:float=8.0;var gravity:float=20.0;private var movedirection:Vector3=Vector3.zero;private var grounded:boolean=false;function Start () {}function FixedUpdate () { if(grounded){  movedirection=Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical"));    //Transforms direction from local space to world space.  movedirection=transform.TransformDirection(movedirection);    movedirection *= speed;    if(Input.GetButton("Jump")){   movedirection.y = jumpspeed;  } }  movedirection.y -= gravity*Time.deltaTime; //Move command  var controller:CharacterController = GetComponent(CharacterController); var flags = controller.Move(movedirection*Time.deltaTime); //CollisionFlags.CollidedBelow  底部发生了碰撞 //CollisionFlags.CollidedSides 四周发生了碰撞 //CollisionFlags.CollidedAbove 顶端发生了碰撞 grounded = (flags & CollisionFlags.CollidedBelow)!=0;}//强制Unity为本脚本所依附的物体增加角色控制器组件@script RequireComponent(CharacterController)


3. 导入3DMax模型

    在3DMax(.fbx文件)把显示单位和系统单位设置为c

  • 1
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值