找回密码
 立即注册
查看: 154|回复: 0

[简易教程] 自学Unity中的常用API笔记与教程,实际用法

[复制链接]
发表于 2024-7-15 18:15 | 显示全部楼层 |阅读模式
private static GameManager _instance;public static GameManager Instance { get => _instance; set => _instance = value; }private void Awake()    {        _instance = this;    }//静态模式为了让其他处所可以提取脚本,记得再Awake赋值,比其他脚本先运行Rigidbody2D rigidbody2D =GetComponent<Rigidbody2D>();//在Start中可以用GetComponent<>中获取自身所有组件,包罗脚本和精灵之类//获取其他对象组件可以用pub公开对象拖拽在用GetComponent<>获取go.AddComponent<Rigibody>();//AddComponent给物体对象添加组件,也可以添加脚本//获取界面里位置数组 定义名=位置.获取子类的位置        Transform[] children=transform.GetComponentsInChildren<Transform>();//不定义数组就是获取第一个foreach (var item in collection)        {        }遍历(对象种类 需要循环的对象也是方式名 关键词 数组)里面可以写一些方式,比如实例化对象Find(””);通过界面名字查找对象 FindWithTag(””);通过标签查找对象//获取X轴摆布Horizontal(X轴+1和-1)float horizontal = Input.GetAxis(”Horizontal”);//获取Y轴摆布Horizontal(Y轴+1和-1)float vertical = Input.GetAxis(”Vertical”);//transform.Translate变形东西,不仅可以移动,还可以变形transform.Translate(new Vector3(horizontal,vertical,0) *2* Time.deltaTime);移动//移动方式(标的目的*移动定义*速度*时间,世界坐标)transform.Translate(Vector3.right * horizotal * Speed * Time.fixedDeltaTime, Space.World);Character Controller角色控制组件go.SimpleMove(位置标的目的,速度)简单移动 受重力影响go.SimpleMove(位置标的目的,速度*Time.deltaTime)移动public Rigdbody go;go.MovePosition(go.transform.position+Vector3.forward*Time.deltaTime);刚体方式移动GameObject bullet= GameObject.Instantiate(bulletPrefab, transform.position, transform.rotation);Rigidbody rd=bullet.GetComponent<Rigidbody>();rd.AddForce(Vector3.forward * 1000);//发射物体需要先获得实例化对象,在用实例化对象获取他的刚体,再用AddForce施加力AddForce(标的目的*力度)rd.velocity = Vector3.forward * 30;//直接给物体速度velocity(标的目的*速度)Time.timeScale=0暂停Time.timeScale=1开始activelnHierarchy 物体和子物体是否禁用显示某带勾组件.enabled=false(封锁这个组件的勾)Destroy()//可以销毁对象,组件,脚本,后面可以加销毁时间Invoke//调用某个方式,方式名,多久调用,InvokeRepeating//持续调用某个方式,方式名,间隔时间,逗留时间void Start(){StartCoroutine(go());IEnumerator go(){yield return null);携程方式书写void Start(){StartCoroutine(go());IEnumerator go(){yield return new WaitForSeconds(3));携程等待三秒Mathf.Abs取绝对值 Mathf.Ceill向上取整hp= Mathf.Clamp(hp,0,100);控制血量不超出Mathf.Floor向下取整Mathf.Lerp(当前位置,方针位置,0-1(二分之一位置,可以写Time.deltaTime*speed));Mathf.MoveTowards(当前X,方针X,移动间距0.1f可以写Time.deltaTime*speed));移动//计算插值(当前X,方针X,移动间距0.1f可以写Time.deltaTime*speed))        Vector2 temp =Vector2.MoveTowards(transform.position,dest,speed);        //获取刚体里的刚体移动给他差值        GetComponent<Rigidbody>().MovePosition(temp);Mathf.Pingpong(当前,方针)来回移动go.position=new Vector(Mathf.Pingpong(Time.time,10),0,0);go.enlerAngles=new Vector(10,0,0),旋转物体用欧拉角go.rotation=Quaternion.Euler(new Vector(10,0,0));Euler把欧拉角转换成四元数Transform player;也可以用刚体旋转,最好用刚体旋转持续旋转用刚体MoveRotationVector3 dir=enemy.position-player.position;获取向量仇敌减本身得到本身到仇敌dir.y=0;这样不会斜视player.rotation=Quaternion.LookRotation(dir);LookRotation本身得视线转移到仇敌Vector3 dir=enemy.position-player.position;dir.y=0;go=Quaternion.LookRotation(dir);player.rotation=Quaternion.Slerp(player.rotaion,go,Time.detaTime);Slerp迟缓向方针旋转Ray ray=new Ray(transform.position+transform.forward,transform.forward);//制作一条向前的射线(位置,标的目的)bool isCollider=Physics.Raycast(ray);判断是否射到物品bool isCollider=Physics.Raycast(ray,1);设置射线最大距离Ray ray=new Ray(transform.position+transform.forward,transform.forward);//制作一条向前的射线(位置,标的目的)RaycastHit hit;定义射线bool isCollider=Physics.Raycast(ray,out hit);返回hit可以用hit调用一些东西hit.transform获取碰到的物体组件hit.collider获取到碰到物体组件hit.point//获取射到物体位置bool isCollider=Physics.Raycast(ray,Mathf.Infinity,LayerMask.GetMask(”Rnemy1”));(射线,无限长(也可以写数字),只和这一层碰撞)Physics.RaycastAll可以检测所有对面物体    public GameObject btn;    start(){                 btn.GetComponent<Button>}().onClick.AddListener()thi.ButtonOnClick);这样就不需要拖拽,直接给按钮加上了事件                }    viod VuttonClick()               {               }private Camerra camera;定义相机void start(){camera=Camerra.main;}获取相机Update(){Ray ray=camera.ScreenPointToRay(Input.mousePosition);定义屏幕发出射线,屏幕发出射线标的目的是鼠标位置RaycastHit hit;定义射线Physics.Raycast(ray,out hit);}返回hit可以用hit调用一些东西SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);从头加载当前场景#if UNITY_EDITOR      UnityEditor.EditorApplication.isPlaying = false;在编纂模式下这样退出#else     Application.Quit();打包后模式下这样退出#endifindex=(index+1)%wayPonts.Length;模加上后达到最大数则又变成0 //循环(位置组件 类名 路径对象的位置组件)        foreach (Transform item in wayPointsGo.transform)        {            //全部添加进类名的位置            wayPoints.Add(item.position);        }游戏物体就可以拿到它下面的路径//清空List中的数组        wayPoints.Clear();AudioSource.PlayClipAtPoint(startClip, Vector3.zero);直接播放音乐pacdotNum = GameObject.Find(”Maze”).transform.childCount;这个文件子对象总数//如果计分板没有封锁        if (gamePanel.activeInHierarchy)//封锁所以携程            StopAllCoroutines();//按下任何键            if (Input.anyKey)//分辩率固定,不全屏        Screen.SetResolution(1024, 768, false);RaycastHit2D hit = Physics2D.Raycast(rb.position, -transform.up,0.4f,LayerMask.GetMask(”groundLayer”));2D碰撞检测        if (hit.collider!=null)        {            isGround = true;        }        else        {            isGround = false;        }nullPointsList.RemoveAt(index);把List里的坐标或物体去除掉//动画组件.赋值Float或者Bool之类(定义的名字“,我们的轴向)        animator.SetFloat(”Horizontal”, horizontal);        animator.SetFloat(”Vertical”, vertical);Physics2D.Raycast(transform.position, Vector2.down, 1f, 1 << 8)发射位置,标的目的,距离,0代表不检测这层,1代表只检测这层private void OnDrawGizmos()    {        Gizmos.DrawLine(transform.position, transform.up);绘制一条有颜色的线,测试用    }collision.CompareTag(”SuperWall”)也是检测标签new Vector3(Mathf.RoundToInt(transform.position.x), Mathf.RoundToInt(transform.position.y));位置取整superWallPointList.Contains(pos)判断List里面有没有PossuperWallPointList.Clear();清空ListAnimator animator;    private void Awake()    {        animator = GetComponent<Animator>();    }    private void Update()    {        //获取动画组件在那层        AnimatorStateInfo info = animator.GetCurrentAnimatorStateInfo(0);        //1播放完,0刚开始&&这个动画名字叫        if (info.normalizedTime>=1&&info.IsName(”BombEffect”))        {            Destroy(gameObject);        }         animator.SetInt(”定义的名字”,轴向)    }tag = ”Wall”;   直接改换标签 gameObject.layer = 8;  直接改换层级//注释下面的变量    [Header(”Stats”)]public float moveSpeed=8f;    private void Update()    {        //移动布景方式        transform.Translate(Vector3.down * moveSpeed * Time.deltaTime);        //获取位置变量        Vector3 postion = transform.position;        //如果Y大于-10,最矮处所        if (postion.y<=-10f)        {            //布景位置=Y加两个这么多            transform.position = new Vector3(postion.x, postion.y+10f*2, 0);        }    }ctrl+shift+F改变相机视角3D模式动画模式用ID来变成“speed”int speedID=Animator.StringToHash(”Speed”);animator.SetFloat(speedID,Input.GetAxis(”Vertical”));
笔记不易!



本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-9-21 11:26 , Processed in 0.087443 second(s), 23 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表