zoukankan      html  css  js  c++  java
  • unity脚本的基础语法

    基本的回调方法

    • Strat()方法:在游戏场景加载时被调用,在该方法内可以写一些游戏场景初始化之类的代码。
    • update():在每一帧渲染之前被调用,大部分游戏代码在这里执行,除了物理部分的代码。
    • Fixedupdate():这个方法会在固定的物理时间调用一次。也是基本物理行为代码执行的地方。

    使用Awake或start方法初始化

         Awake方法是在加载场景时运行;start方法是在第一次调用Update或FixedUpdate方法之前被调用;Awake方法运行在所有Start方法之前。

    协同程序(Coroutines)

         返回值类型为IEnumerator类型 

    IEnumerator SomeCoroutine(){
       yield return 0;//等待1帧
       yield return new WaitForSeconds(2);//等待2s
    }

    脚本常用操作

    void Update(){
        this.transform.Rotate(20,0,0,Space.World);//相对于世界坐标绕X轴旋转20
        this.transform.Translate(0,0,1);//实现物体每帧向前移动1个单位
        this.transform.Translate(0,0,1,Space.Self);//相对于自身轴
        this.transform.Rotate(20*Time.deltaTime,0,0,);//绕X轴匀速旋转
    
        Vector3 a=gameObject.transform.positon;//获取对象位置坐标
        a.y +=5*Time.deltaTime;//沿Y轴每秒上升5个单位
        gameObject.transform.positon=a;//设置新的位置坐标

    Unity中的坐标

    X轴为红色的轴表示左右,y轴为绿色表示上下。Z轴为蓝色表示前后

    访问游戏对象组件

    GetComponent<>();//获得组件

    transform.Find("");//获得子对象

    transform.parent.Translate(0,0,1);//找到父对象并将其移动


    foreach (Transform child in transform){//循环获取所有的子对象

    child.Translate(0,5,0);

    }

    通过名字或标签获取对象

    GameObject name =GameObject.Find("somename");//获取名称为somename的游戏对象

    GameObject tag =GameObject.FindWithTag("sometag");//获取标签名为sometag的游戏对象

    通过传递参数获取对象

    void OnTriggerStay(Collider other){

       if(other.GetComponent<Rigidbody>()){

       other.GetComponent<Rigidbody>().AddForce(0,0,2);}}

    通过组件名称获取对象

    void Start(){

      Test test=FindObjectOfType<Test>();//获取第一个找到的test组件

      Debug.Log(test.gameObject.name);//打印挂有test组件的对象的名称

      Test[] tests=FindObjectsOfType<Test>();//获取所有找到的test组件

       foreach(Test a in tests){

          Debug.Log(a.gameObject.name);//打印挂有test组件的所有对象的名称

    }}

    实例化游戏对象Instantiate(gameObject,transform.position);

  • 相关阅读:
    字母图形
    IBM CEO罗睿兰:科技公司屹立百年的3个秘诀
    Uva 1331
    js 推断字符串是否包括某字符串
    Verilog堵塞赋值与非堵塞赋值
    tabBar颜色改动
    零基础学python-4.2 其它内建类型
    怎样给你的Android 安装文件(APK)瘦身
    Ambari-部署常见问题
    ops
  • 原文地址:https://www.cnblogs.com/qichun/p/6227652.html
Copyright © 2011-2022 走看看