Unity_常用的一些方法记录

1 篇文章 0 订阅

1.通过物体名字查找游戏物体

GameObject.Find(“Cube”);//查找名为Cube的游戏物体

GameObject.Find(“GameObject/Canvas/Text”);//可以指定路径位置

2.查找对象中的组件

GameObject.GetComponent<组件名称>();

3.调用其他对象下组件中的方法

GameObject.Find(“脚本所在的物体的名字”).SendMessage(“函数名”); //能调用public和private类型函数
GameObject.Find(“脚本所在的物体的名字”).GetComponent<脚本名>().函数名(); //只能调用public类型函数

4.打印数据

Debug.Log(“打印内容”);

5.获得/设置物体的locaiton、rotation、scale

  • 位置:

Vector3 player_postion = this.transform.position;// 获取Player变量指定的对象的(X,Y,Z)

// 获取X,Y,Z值

float x = player_postion.x;

float y = player_postion.y;

float z = player_postion.z;

//设置位置

// 1.直接赋值

this.transform.position = player_postion;

// 2.在某GameObject的基础上加

this.transform.position = new Vector3(player_postion.x, player_postion.y + 7.79F, player_postion.z - 15);

//或者是

this.transform.position = player_postion + new Vector3(0, 7.79F, -15);

  • 旋转:

this.transform.eulerAngles //获得旋转

this.transform.localEulerAngles=new Vector3(float Pitch,float Yaw,float Roll); //设置绝对旋转

  • 缩放:

this.transform.localScale //获得缩放

this.transform.localScale = new Vector3(x, y,z);//修改缩放

6.两点间的距离

Vector3.Distance(a,b) //a和b是两个点的坐标position值

7.unity与web间(webgl/webplayer)的传输:传出、传入

  • 传出:

在unity中写如下调用语句:
Application.ExternalCall( “SayHello”, “The game says hello!” );

在html中定义函数如下
function SayHello(args){
alert(args);
}

  • 传入:

在unity中定义函数如下,并将带有FunctionName函数的脚本绑定到Main Camera中

HTML中写:
SendMessage(“Main Camera”, “FunctionName”, 参数);//向unity中的Main Camera对象下的FunctionName函数传入参数
SendMessage方法只能传递一个参数,不然会报错,所以通常传递多个参数的时候,将数据组成json数据,以string的形式传入

8.lerp插值运算

从A点过渡到B点

Transform.position = Vector3.Lerp(A点坐标, B点坐标, alpha);//alpha过渡值:0时取A,1时取B,将alpha从0过渡到1即可

9.修改物体的材质

this.GetComponent().material = 新材质;

10.将变量暴露给编辑器,方便在编辑器中手动修改

C#中将变量设置为公开:
public flaot f;

public Vector3 position;

11.用代码 给物体添加组件,脚本

Unity5.x以前
创建一个对象并且给它添加脚本和组件
gameObject.AddComponent ();//添加刚体
gameObject.AddComponent ();//添加碰撞器
gameObject.AddComponent ();//添加脚本

Unity 2017.x之后
方式一
SphereCollider sc = gameObject.AddComponent(typeof(SphereCollider)) as SphereCollider;
方式二
SphereCollider sc = gameObject.AddComponent() as SphereCollider;

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值