返回首页DA系统C#IDE文件同步服务屏保 今天是: 2026-05-05    "立夏"  夏季的第一个节气,表示盛夏时节的正式开始

搜索
热搜: linux 技术
Hi~登录注册
查看: 2648|回复: 0

[原创] 【原创】简单讲解Unity里面常用的API

[复制链接]
发表于 2021-3-7 21:35:47 | 显示全部楼层 |阅读模式
本帖最后由 da11 于 2021-3-15 09:38 编辑



//图片和附件要登陆之后才能查看哦,各位大侠们!
//以下讲解Compon类


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class testDemo : MonoBehaviour
{
    ///<summary>
        ///简单讲解脚本改变物体Cube组件属性
        ///</summary>

    //以后测试Unity代码可以用以下语句
    private void OnGUI()
    {
        if (GUILayout.Button("瞬移"))
        {
            Debug.Log("this.transform");
            //调用脚本挂在物体上的transform类,在使用position方法,根据提示,此方法需要初始化Vector3类型,并赋值(x,y,z位置)

            //注意,因为是继承MonoBehaviour的类脚本,所以,他能使用父成员MonoBehaviour类的方法,而MonoBehaviour之上的类也是被MonoBehaviour继承。
            //说到底position也是MonoBehaviour继承父类成员


            this.transform.position = new Vector3(0, 2, 1);         

            //this.GetComponent<Transform>().position = new Vector3(0, 0, 0);
        }

        if (GUILayout.Button("变色"))
        {
            Debug.Log("GetComponent");
            //更改物体颜色,注意:现在的组件一般除了transform类可以直接点,所有组件,都需要使用   GetComponent<【组件名称】>()   来调用!包括特殊的transform类都可以GetComponent<【组件名称】>()调用

            //颜色的RGB每项都要除255才能最后给脚本,不然最后结果可能与你不符哦!!

            //this.GetComponent<MeshRenderer>().material.color = new Color(255, 0, 255);
            this.GetComponent<MeshRenderer>().material.color = Color.yellow;
        }

        if (GUILayout.Button("恢复默认"))
        {
            Debug.Log("恢复默认");
            this.transform.position = new Vector3(0, 0, 0);
            this.GetComponent<MeshRenderer>().material.color = new Color(0, 0, 0);

        }

        if (GUILayout.Button("测试按钮-获取当前物体的所有组件"))
        {
            Debug.Log("测试开始,获取当前物体的所有组件");
            //Component[] ComSZ  = this.GetComponents<Component>();
            var ComSZ = this.GetComponents<Component>();
            foreach (var item in ComSZ)
            {
                //以下两行都可以显示组件的名称
                //Debug.Log(item);
                Debug.Log(item.GetType());
            }
        }

        if (GUILayout.Button("测试按钮-获取后代物体的指定组件"))
        {
            //获取物体某一个组件(包括组件父类)和这个子类物体的组件,获取多个需要GetComponentsInChildren<Type>();,注意有方法有s
            //不通俗说法:获取后代物体的指定组件(从自身开始)
            Debug.Log("测试开始,获取后代物体的指定组件");
            Component[] test01SZ = GetComponentsInChildren<Component>();


            foreach (var item in test01SZ)
            {
                //Debug.Log(item);
                Debug.Log(item.GetType());
                Debug.Log(item.name);

                //将数组中所有的物体改成红色
                item.GetComponent<MeshRenderer>().material.color = Color.red;
            }

            Debug.Log(test01SZ.Length);
        }

        if (GUILayout.Button("测试按钮-获取先辈物体的指定组件"))
        {
            //获取物体某一个组件(包括组件父类)和这个父类物体的组件,获取多个需要GetComponentsInParent<Type>();,注意有方法有s
            //不通俗说法:获取先辈物体的指定组件(从自身开始)
            Debug.Log("测试开始,获取先辈物体的指定组件");
            Component[] test02SZ = GetComponentsInParent<Component>();


            foreach (var item in test02SZ)
            {
                //Debug.Log(item);
                Debug.Log(item.GetType());
                Debug.Log(item.name);
            }

            Debug.Log(test02SZ.Length);
        }

    }
}

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册成为修仙之旅的少年~

x
 楼主| 发表于 2021-3-7 23:01:56 | 显示全部楼层
//可以通过圣典查找 “Component ”来查看相应中文文档


本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册成为修仙之旅的少年~

x
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-3-8 00:40:04 | 显示全部楼层
本帖最后由 da11 于 2021-3-14 23:23 编辑

//以下讲解Transform变换物体组件的基本使用方法

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TransformDemo : MonoBehaviour
{
    ///<summary>
    ///Transform类提供了查找(父、根、子)变换组件、改变位置、角度、大小功能
    ///</summary>

    /*

    // Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{

}

    */

    public Transform tf;


    private void OnGUI()
    {
        if (GUILayout.Button("恢复位置"))
        {
            this.transform.position = new Vector3(0, 0, 0);
            this.transform.rotation = new Quaternion(0, 0, 0,0);

            foreach (Transform child in this.transform)
            {
                child.position = new Vector3(0,0,0);
            }
        }

        if (GUILayout.Button("Transform组件测试按钮1"))
        {
            //遍历Transform组件的物体名字及改变其世界坐标
            Debug.Log("物体名字是:" + this.transform.name + " 对应的世界坐标:" + this.transform.position);
            int xWZ = 1;
            //Transform child = this.GetComponent<Transform>();
            foreach (Transform child in this.transform)
            {
                //child为每个子物体的变换组件(只能遍历一代子物体)
                //child.position += Vector3.up * 10.0F;
                //print(child.name);

                //为每个遍历的子物体变换世界空间位置--position属性
                child.position = new Vector3(0 + xWZ, 0 + xWZ);
                Debug.Log("物体名字是:"+child.name+" 对应的世界坐标:"+child.position);

                xWZ++;
            }
        }

        if (GUILayout.Button("Transform组件测试按钮2"))
        {
            //首先更改父物体的世界坐标
            this.transform.position = new Vector3(2, 3, 1);

            //遍历Transform组件的物体名字及改变其相对父物体轴心点的坐标
            Debug.Log("物体名字是:" + this.transform.name + " 对应的世界坐标:" + this.transform.position);
            float xWZ = 1;
            //Transform child = this.GetComponent<Transform>();
            foreach (Transform child in this.transform)
            {
                //child为每个子物体的变换组件(只能遍历一代子物体)
                //child.position += Vector3.up * 10.0F;
                //print(child.name);

                //为每个遍历的子物体变换相对父物体轴心点的位置--localPosition属性
                child.localPosition = new Vector3(0 + xWZ, 0 + xWZ);
                Debug.Log("物体名字是:" + child.name + " 对应的世界坐标:" + child.position);

                xWZ+=0.5F;
            }
        }

        if (GUILayout.Button("Transform组件测试按钮3"))
        {
            //相对与世界坐标旋转角度的属性
            this.transform.rotation = new Quaternion(0, 90, 0, 0);

            //相对与父类物体旋转角度的属性
            this.transform.localRotation = new Quaternion(0, 90, 0, 0);

            //相对与父类物体缩放比例的属性
            this.transform.localScale = new Vector3(1, 2, 1);

            //可以理解为:物体与模型缩放比例(自身缩放比例*父物体缩放比例)
            //this.transform.lossyScale
            //如:父物体localScale为3,当前物体localScale为2,则lossyScale为6
        }

        //GUILayout类型的RepeatButton方法代表这个按钮不松手,则会一直执行(重点)
        if (GUILayout.RepeatButton("Transform组件测试-平移方法"))
        {
            //向自身坐标系Z轴移动一米(根据物体自身的坐标移动)
            //this.transform.Translate(0, 0, 1);

            //向世界坐标系Z轴移动一米(根据场景界面的世界坐标移动)
            //this.transform.Translate(0, 0, 1,Space.World);

            //向自身坐标系Z轴旋转一度(根据物体自身的坐标旋转)
            //this.transform.Rotate(0, 0, 1);

            //向世界坐标系Z轴旋转一度(根据场景界面的世界坐标旋转)
            //this.transform.Rotate(0, 10, 0, Space.World);

            //小知识:Vector3类型的zero属性是世界原点(重点!)
            //Vector3类型的up属性是世界的y轴

            /*Vector3类型的常用属性代表的xyz轴为:(重点)
             * up,0,1,0
             * down,0,-1,0
             * left,-1,0,0
             * right,1,0,0
             * forward,0,0,1
             * back,0,0,-1
             * zero,0,0,0
             * one,1,1,1
            */

            //transform.RotateAround方法两个形参的重载已经否决,只有三个形参的重载还保留
            //第一个参数的含义是,从哪个点开始,第二个参数是沿那个轴,第三个参数是围绕角度(一帧转的角度)
            this.transform.RotateAround(Vector3.zero, Vector3.up, 1);

            Debug.Log("现在的坐标,x轴: "+this.transform.position.x +" y轴: "+ this.transform.position.y +" z轴: "+ this.transform.position.z);
            Debug.Log("现在的角度,x轴角度: " + this.transform.rotation.x + " y轴角度: " + this.transform.rotation.y + " z轴角度: " + this.transform.rotation.z);

        }

        if (GUILayout.Button("获取根物体的transform组件按钮"))
        {
            Transform rootTransObj =  this.transform.root;
            Debug.Log(rootTransObj.name);
        }

        if (GUILayout.Button("获取父物体的transform组件按钮"))
        {
            Transform parentTransObj = this.transform.parent;
            Debug.Log(parentTransObj.name);
        }

        if (GUILayout.Button("设置父物体"))
        {
            //this.transform.SetParent默认第二个参数是bool值true
            //设置父物体:当前物体的位置视为世界坐标
            //this.transform.SetParent(tf);

            //设置父物体:当前物体的位置视为localPosition(自身坐标)
            this.transform.SetParent(tf, false);
        }

        if (GUILayout.Button("查找子物体"))
        {
            //根据名称获取子物体
            //this.transform.Find("【写要查找的子物体名称】");
            //注意,查找子物体可以使用Find,在子物体下一级的子物体,Find要加斜杠“/”标明路径才可以查找,可以有多个斜杠,如下
            //this.transform.Find("【写要查找的子物体名称/在下一级的子物体名称/第3级的子物体名称/第4级的子物体名称】");
            //温馨提示:不建议这么写
            //Transform childTrans =  this.transform.Find("Cube");

            //查找子物体的数量有多少
            int childCountNum = this.transform.childCount;

            for (int i = 0; i < childCountNum; i++)
            {
                //this.transform.GetChild是根据索引获取子物体transform组件的方法
                //for循环将this.transform.GetChild索引,获取到的给childTrans
                Transform childTrans = this.transform.GetChild(i);
            }

        }


        if (GUILayout.Button("练习按钮-查找子物体"))
        {
            Transform checkChildOBJ = GetNameFindGameObject.GetNameFindGameObjectSF(this.transform, "Cube (24)");
            //GetNameFindGameObject.DGFindChild(this.transform, "Cube (5)");

            if (checkChildOBJ != null)
            {
                Debug.Log("已找到 " + checkChildOBJ.name + " 的游戏物体");
                checkChildOBJ.GetComponent<MeshRenderer>().material.color = Color.yellow;
            }
            else
            {
                Debug.Log("没有找到游戏物体");
            }




        }

        if (GUILayout.Button("解除孩子关系和父子"))
        {
            //解除Cube(5)的孩子关系
            //GetNameFindGameObject.GetNameFindGameObjectSF(this.gameObject, "Cube (24)").transform.DetachChildren();

            //将Cube (5)父物体设置为null
            //GetNameFindGameObject.GetNameFindGameObjectSF(this.gameObject, "Cube (24)").transform.SetParent(null);

        }
    }

}

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册成为修仙之旅的少年~

x
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-3-8 00:40:45 | 显示全部楼层

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册成为修仙之旅的少年~

x
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-3-14 23:11:18 | 显示全部楼层
本帖最后由 da11 于 2021-3-14 23:20 编辑

//需要思考的递归练习!!




//GetNameFindGameObject.cs
//练习需联动Transform上例的查子物体按钮方法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class GetNameFindGameObject : MonoBehaviour
{


    //练习:在层级未知的情况下查找一个名称为“childname”的子物体
    //使用递归
    //根据物体名称查找子物体是否存在,存在则返回Transform组件类型,不存在则返回空
    /*
    public static Transform DGFindChild(Transform check,string name)
    {
         Transform checkName = null;
         //GetComponentsInChildren查找后代(所有代)的组件方法
         foreach (Transform t in check.GetComponentsInChildren<Transform>())
         {
             if (t.name == name)
             {
                 Debug.Log("成功获得子物体: " + t.name);
                 return t;               
             }        

         }
         return checkName;
    }
    */
    /// <summary>
    /// 在层级未知的情况下查找子物体
    /// </summary>
    /// <param name="GOTF">父物体变换组件</param>
    /// <param name="name">要查找的子物体名称</param>
    /// <returns></returns>
    public static Transform GetNameFindGameObjectSF(Transform GOTF,string name)
    {
        Transform childName = GOTF.Find(name);

        if (childName != null)
        {
            return childName;
        }

        for (int i = 0; i < GOTF.childCount; i++)
        {
            childName = GetNameFindGameObjectSF(GOTF.GetChild(i), name);
            if (childName != null)
            {
                return childName;
            }
        }

        return null;
    }
}




回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-3-14 23:13:10 | 显示全部楼层
//以下讲解GameObject

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameObjScriptDemo : MonoBehaviour
{
        ///<summary>
        ///讲解游戏对象类,功能,获取游戏对象,查找(根据名称、标签、组件)游戏对象
        ///</summary>

        /*

        // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

        */

    private void OnGUI()
    {
        if (GUILayout.Button("GameObj类的基本讲解按钮"))
        {
            //在场景中物体激活的状态(物体实际激活状态)
            //显示当前物体是否被激活,如果父物体被禁用,但是this在子物体中,且没有禁用,这个activeInHierarchy变量会显示父物体的禁用状态
            bool test = this.gameObject.activeInHierarchy;
            print(test);

            //物体自身激活的状态(物体右上角的勾)
            //显示当前物体是否被激活,如果父物体被禁用,this在子物体中,且没有禁用,activeSelf变量只会显示this物体的禁用状态
            //不过此时一般父子物体禁用了,this会无效,除非限定物体名
            bool test1 = this.gameObject.activeSelf;
            print(test1);


        }

        if (GUILayout.Button("新建一个游戏物体"))
        {
            //创建一个游戏物体cubeLight,注意,只有GameObject类型才能使用构造函数new!!
            GameObject cubeLight = new GameObject();

            //将刚刚新建的游戏物体添加光组件,然后赋值光组件的引用给lightC,这样,以后调用lightC即可控制cubeLight物体的光组件
            Light lightC = cubeLight.gameObject.AddComponent<Light>();

            //给光组件赋值为黄色
            lightC.color = Color.yellow;
            lightC.type = LightType.Point;
        }

        if (GUILayout.Button("查找物体名称"))
        {
            //GameObject.Find提供了在场景中根据名称查找物体的方法(慎用)
            GameObject Objname = GameObject.Find("Cube (4)");
            if (Objname == null)
            {
                print("没有找到物体");
            }
            else
            {
                print("找到了 " + Objname.name + " 的游戏物体");
                print("反手就把 " + Objname.name + " 禁用掉,哼~");
                Objname.gameObject.SetActive(false);

            }

            //获取所有使用该名字标签的物体(数组)
            GameObject[] ObjNameSZ  = GameObject.FindGameObjectsWithTag("tag");

            ////获取使用该名字标签的物体(单个)
            GameObject ObjName = GameObject.FindGameObjectWithTag("tag");
        }

    }

    private void OnMouseUp()
    {
        //恢复Cube4下的第一个子物体为true状态
        Transform TF1 = this.transform.GetChild(0);
        TF1.gameObject.SetActive(true);
    }

    private void OnMouseDown()
    {
        //设置Cube4下的第一个子物体为false状态
        Transform TF1 = this.transform.GetChild(0);
        TF1.gameObject.SetActive(false);
    }
}

回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-3-14 23:13:43 | 显示全部楼层

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册成为修仙之旅的少年~

x
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-3-14 23:15:16 | 显示全部楼层
//以下讲解Object类型

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjScript : MonoBehaviour
{
        ///<summary>
        ///根据类型名称查找这个类型或者类型组合和销毁游戏对象
        ///</summary>

        /*

        // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

        */

    private void OnGUI()
    {
        if (GUILayout.Button("Obj类型基本讲解-销毁对象"))
        {
            //销毁一个游戏对象
            Object.Destroy(GameObject.Find("Cube (4)"));
        }

        if (GUILayout.Button("Obj类型基本讲解-查找对象"))
        {
            //根据类型名称查找这个类型或者类型组合
            Object.FindObjectOfType<Transform>();
            Object.FindObjectsOfType<Light>();
        }
    }
}

回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-3-14 23:15:36 | 显示全部楼层

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册成为修仙之旅的少年~

x
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-5-30 22:05:47 | 显示全部楼层
//左右移动,Vector3坐标使用的是X轴!!

        if (Input.GetButton("Horizontal"))  //检测虚拟按钮Horizontal,对应的绑定按键为d、a、小键盘右、小键盘左
        {
            PlayerTransform.Translate(new Vector3(Input.GetAxis("Horizontal"), 0, 0) * PlayerWalkSpeed);
        }



//上下移动,Vector3坐标使用的是Z轴!!

        if (Input.GetButton("Vertical"))  //检测虚拟按钮Vertical,对应的绑定按键为s、w、小键盘下、小键盘上
        {
            PlayerTransform.Translate(new Vector3(0, 0, Input.GetAxis("Vertical")) * PlayerWalkSpeed);
        }

回复 支持 反对

使用道具 举报

游客
回复
*滑块验证:

DA论坛飞机票来了~
快速回复 返回顶部 返回列表