C#从零开始学习(用unity编写C#代码)(unity Lab2)

这是书本中第二个unity Lab,在这次实验中,将学习如何使用C#编写代码

用unity编写C#代码

本次将完成的工作

  1. 为GameObject添加一个C#脚本
  2. 用Visual Studio编写这个脚本
  3. 在Unity播放游戏
  4. 调试代码

为GameObject添加一个C#脚本

首先点击想要添加代码的对象
然后在Add Compoent -> New script -> Create And Add
在这里插入图片描述
这样就可以在Assets中出现C#脚本

用Visual Studio编写这个脚本

双击文件就可以跳转到Vistual Studio,如果不能跳转

第一步:关闭当前的visual studio ,然后开点unity。
第二步:在工具栏左上角找到Edit-->preferences 点击进入	
第三步:之后进入External Tools 修改 External Scripts Editor 点击选择自己的下载的visual studio 版本。
第四步:重启visual studio就会发现脚本关联了。

编写代码使球体旋转

    void Update()
    {

        transform.Rotate(Vector3.up, 180 * Time.deltaTime);
    }

transform.Rotate使对象旋转
Time.deltaTime为每帧的时间

为类添加旋转角度和速度字段

    public float XRotation = 0;
    public float YRotation = 1;
    public float ZRotation = 0;
    public float DegreesPersecond = 180;
        void Update()
    {
        Vector3 axis = new Vector3(XRotation, YRotation, ZRotation);
        transform.Rotate(axis, DegreesPersecond * Time.deltaTime);
    }

添加的字段在Unity中可以查看并直接更改
在这里插入图片描述
在运行过程中可以直接更改,停止后会返回原来的数值

文章介绍了一种debug用来观测3D向量如何工作的

    void Update()
    {
        Vector3 axis = new Vector3(XRotation, YRotation, ZRotation);
        transform.Rotate(axis, DegreesPersecond * Time.deltaTime);
        Debug.DrawRay(Vector3.zero, axis, Color.yellow, .5f);
    }

使用了Debug.DrawRay函数,不过看不明白,就只提出来记录一下

绕一点旋转

把球的位置改为5,这样球会绕着中心旋转

    void Update()
    {
        Vector3 axis = new Vector3(XRotation, YRotation, ZRotation);
        transform.RotateAround(Vector3.zero, axis, DegreesPersecond * Time.deltaTime);
    }

调试代码

首先在Unity中停止游戏,然后在Vistual Studio中打断点
在这里插入图片描述
在这里插入图片描述
这意味着每运行x次,断点才会停止

至此,我们就学习完了第Unity_Lab2,然后让我们复习一下本章讲了什么

  • 学习了为GameObject添加一个C#脚本
  • 学习了Visual Studio编写这个脚本
  • 学习了对象的旋转操作
  • 学习了如何调试代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值