Unity脚本相关(常用易忽略方法总结)

脚本生命周期

在这里插入图片描述

FixedUpdate中调用物理相关运算

脚本变量在inspector操作

[HideInHireachy]
public int nowSpeed;
[Range(0,1)]
public int maxSpeed;
[Serializable]
public class TestClass{
    public int a;
    public int b;
}

组件相关代码编写

///transform相关
transform.rotation=new Quaternion(transform.rotation.x,transform.rotation.y,transform.rotation.z,transform.rotation.w);//赋值transform的rotation
transform.Translate(Vector.up*Time.deltaTime,Space.World);
transform.Translate(Vector.up*Time.deltaTime,Space.Self);
transform.RotateAround(Vector3.up,Time.deltaTime);
//AudioSource相关
AudioSource audio;

[RequireComponent(typeof(AudioSource))]
class TheScript
{
    public AudioClip clip;//音效片段
    void Start()
    {
        audio = gameObject.GetComponent<AudioSource>();
        //audio = (AudioSource)gameObject.GetComponent("AudioSource");
        audio.clip = clip;
        audio.Play();
    }
}

Time类相关方法

Time.time;//表示游戏从开始到现在运行的时间
Time.deltaTime;//每帧之间的间隔
Time.fixedDeltaTime;//FixedUpdate 调用的时间
Time.timeScale;//实现加速、减速、暂停
Time.frameCount;//游戏帧数
Time.frameCount/Time.time;//游戏运行的帧率

数学相关的类

Random.Range(0,10);//0~9
Random.rotation;//随机产生旋转角度
Random.rotationUniform;//随机的角度比较均匀
Random.value;//从0到1的随机数
Random.seed = 1;

Mathf.Abs(-10);
Mathf.Ceil(1.12f);
Mathf.Clamp(100,0,10);//返回在0~10之间的数
Mathf.Floor(1.2f);
Mathf.Lerp(1,10,0);//两个数之间的值:1
Mathf.Lerp(1,10,0.5f);//两个数之间的值:5.5
Mathf.PI;//圆周率


void Update()
{
    timer += Time.deltaTime;//若*0.5,则将以2s的速度完成
    //插值实现运动
    transform.position = new Vector3(Mathf.Lerp(start.x,target.x,timer),0,0);
    //平滑的运动
    transform.position = new Vector3(Mathf.SmoothStep(start.x,target.x,timer),0,0);
    //朝向某个点运动,为了使物体运动下去,这个点不能是固定的。
    transform.position = new Vector3(Mathf.MoveTowards(transform.position.x,5,0.5f),0,0);
}

制作中常用方法

Gameobject cube = Gameobject.Find("Cube/Cube1");//少使用,尽量写明路径
GameObject.Instantiate(cube);//场景中的物体或者预制体进行复制
GameObjec.Destory(gameobject,2)//2s销毁
GameObjec.Destory(GetComponent<BoxColider>(),2)//2s销毁
Invoke("Hello"2);//不能传参
InvokeRepeating("Hello"2,2);//两秒调用一次

public void Hello()
{
    CancelInvoke("Hello");//取消重复调用
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值