Unity——C#脚本常用类和组件介绍

Vector 结构体

Vector3

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

public class Vector : MonoBehaviour
{
// Start is called before the first frame update
void Start()
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Vector : MonoBehaviour {
    // Start is called before the first frame update
    void Start() {
        // 可作为:向量,坐标,旋转,缩放
        Vector3 v = new Vector3();
        //v = Vector3.zero;
        //v = Vector3.one;
        //v = Vector3.forward;
        //v = Vector3.back;
        //v = Vector3.up;
        //v.x = 0;
        //v.y = 0;
        //v.z = 0;
        v = Vector3.right;

        Vector3 v2 = Vector3.forward;

        // 计算两个向量夹角
        Debug.Log(Vector3.Angle(v, v2));
        // 计算两点之间的距离
        Debug.Log(Vector3.Distance(v, v2));
        // 点乘
        Debug.Log(Vector3.Dot(v, v2));
        // 叉乘
        Debug.Log(Vector3.Cross(v, v2));
        // 插值(在2个向量之间进行比例计算)
        Debug.Log(Vector3.Lerp(Vector3.zero, Vector3.one, 0.5f));
        // 向量的模
        Debug.Log(v.magnitude);
        // 规范化的向量
        Debug.Log(v.normalized);
    }

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

    }
}


Quaternion 旋转

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

public class Rotate : MonoBehaviour {
    // Start is called before the first frame update
    void Start() {
        // 旋转:欧拉角,四元数
        Vector3 rotate=new Vector3(0,30,0);// 沿着Y转30度
        Quaternion quaternion=Quaternion.identity;// 无旋转的四元数
        // 欧拉角转化为四元数
        quaternion = Quaternion.Euler(rotate);
        // 四元数转换为欧拉角
        rotate = quaternion.eulerAngles;
        // 看向一个物体
        quaternion = Quaternion.LookRotation(new Vector3(0, 0, 0));
    }

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

    }
}

Debug 调试类

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

public class DebugTest : MonoBehaviour {
    // Start is called before the first frame update
    void Start() {
        Debug.Log("Test");
        Debug.LogWarning("TestWarning");
        Debug.LogError("TestError");
    }

    // Update is called once per frame
    void Update() {
        // 绘制一条线 起点,终点
        Debug.DrawLine(new Vector3(1, 0, 0), new Vector3(1, 1, 0), Color.blue);
        // 绘制一条射线 起点,射线方向
        Debug.DrawRay(new Vector3(1, 0, 0), new Vector3(1, 1, 0), Color.red);
    }
}

image.png

GameObject 游戏对象类

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

public class Empty : MonoBehaviour {
    public GameObject square;
    // 获取预设体
    public GameObject preFab;

    // Start is called before the first frame update
    void Start() {
        // 拿到当前脚本所挂在的游戏物体
        GameObject go = this.gameObject;
        // 游戏物体名称
        Debug.Log(go.name);
        // 标签 tag
        Debug.Log(go.tag);
        // 图层 layout
        Debug.Log(go.layer);
        // 打印正方形square的名称(这里在Unity上,在当前对象go里绑定给其他游戏物体对象Square)
        Debug.Log(square.name);
        Debug.Log(square.activeInHierarchy);// 当前真正的激活状态
        Debug.Log(square.activeSelf);// 当前自身的激活状态
        square.SetActive(true);// 设置激活状态
        // 获取Transform组件
        Transform trans = this.transform;
        Debug.Log(trans.position);
        // 获取其他组件
        BoxcastCommand bc = GetComponent<BoxcastCommand>();
        // 获取当前物体的子物体身上的某个组件 GetComponentInChildren
        // 获取当前物体的父物体身上的某个组件 GetComponentInParent
        // 添加一个组件
        gameObject.AddComponent<AudioSource>(); // 当前对象添加
        square.AddComponent<AudioSource>(); // 子对象添加
        // 通过游戏物体名称获取其他游戏物体
        GameObject test = GameObject.Find("Test");
        Debug.Log(test.name);
        // 通过游戏标签来获取游戏物体
        test = GameObject.FindWithTag(test.tag);
        Debug.Log(test.tag);
        // 通过预设体来实例化一个游戏物体
        Instantiate(preFab);
        Instantiate(preFab, trans);// 创建trans的子对象preFab
        GameObject goo = Instantiate(preFab, Vector3.zero, Quaternion.identity);// 创建放到0,0,0位置上不旋转的preFab
        // 销毁游戏对象
        Destroy(goo);
    }

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

    }
}

image.png

Time 时间类

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

public class TimeTest : MonoBehaviour
{
    private float timer = 0;

    // Start is called before the first frame update
    void Start()
    {
        // 游戏开始到现在所花的时间
        Debug.Log(Time.time);
        // 时间缩放值(游戏加速/减速,暂停)
        Debug.Log(Time.timeScale);
        // 固定时间间隔
        Debug.Log(Time.fixedDeltaTime);
       
    }

    // Update is called once per frame
    void Update()
    {
        // 计时器
        timer += Time.deltaTime;
        // 上一帧到这一帧所用的游戏时间  60帧,1/60
        Debug.Log(Time.deltaTime);
    }
}

Application 类

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

public class ApplicationTest : MonoBehaviour {
    // Start is called before the first frame update
    void Start() {
        // (只读,加密压缩)获得游戏数据文件路径 Assets目录 ,(+"/新建文件.txt")  
        Debug.Log(Application.dataPath);
        // (可写的)持久化文件夹路径
        Debug.Log(Application.persistentDataPath);
        // StreamingAssets文件夹路径(只读,但不会加密压缩,一般放不需要加密,可以看见的文件)
        Debug.Log(Application.streamingAssetsPath);
        // 临时文件夹
        Debug.Log(Application.temporaryCachePath);
        // 控制是否在后台运行
        Debug.Log(Application.runInBackground);
        // 打开url
        Application.OpenURL("https://www.baidu.com/");
        // 退出游戏
        Application.Quit();
    }

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

    }
}

场景相关类 Scene、SceneManager

image.png

(1)选择左上角的“文件”
(2)选择“生成设置”
(3)看到“Build 中的场景”
(4)image.png

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

public class SceneBreak : MonoBehaviour {
    // Start is called before the first frame update
    void Start() {
        // 两个类,场景类,场景管理类
        // 场景跳转
        SceneManager.LoadScene(1);// 1代表在“Build 中的场景”中的序号索引对应的场景
        SceneManager.LoadScene("MyScene");// 根据场景名称进行跳转
        // 获取当前场景
        Scene scene = SceneManager.GetActiveScene();
        Debug.Log(scene.name);
        // 场景是否已经加载
        Debug.Log(scene.isLoaded);
        // 场景路径
        Debug.Log(scene.path);
        // 场景索引
        Debug.Log(scene.buildIndex);
        // 获取场景所有根数组
        GameObject[] gos = scene.GetRootGameObjects();
        Debug.Log(gos.Length);

        // 场景管理类
        // 创建新场景
        Scene newScene = SceneManager.CreateScene("newSceneName");
        // 当前已经加载了场景(激活的场景)的数量
        Debug.Log(SceneManager.sceneCount);
        // 卸载场景(异步销毁,另一个被弃用了)
        SceneManager.UnloadSceneAsync(newScene);
        // 加载场景(同步)
        SceneManager.LoadScene("MyScene",LoadSceneMode.Additive);// 根据场景名称进行跳转      Additive 添加了MyScene ;Single 添加MyScene,去掉了当前的Scene
    }

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

    }
}

异步加载场景和读取进度条

同步和异步的区别:
image.png

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

public class SceneLoadAsync : MonoBehaviour {
    AsyncOperation operation;

    // Start is called before the first frame update
    void Start() {
        StartCoroutine(LoadScene());
    }

    // 协程方法(用来异步加载场景)  固定的返回类型:IEnumerator
    IEnumerator LoadScene() {
        operation = SceneManager.LoadSceneAsync(1);
        // 加载完场景后,不要自动跳转,手动跳转
        operation.allowSceneActivation = false;
        yield return operation;
    }

    // 定时器,这里用来控制场景加载后的跳转
    float timer = 0;

    // Update is called once per frame
    void Update() {
        // 每一帧实时打印 场景加载进度,0~0.9
        Debug.Log(operation.progress);

        timer += Time.deltaTime;
        // 如果达到5s再异步跳转场景
        if (timer > 5) {
            operation.allowSceneActivation = true;
        }
    }
}

脚本中使用 Transform

每个游戏对象都有Transform,包含位置、旋转和缩放。

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

public class TransformTest : MonoBehaviour {
    // Start is called before the first frame update
    void Start() {
        // 获取位置
        Debug.Log(transform.position);// 相对世界的位置
        Debug.Log(transform.localPosition);// 相对于它的父物体的位置
        // 获取旋转
        Debug.Log(transform.rotation);
        Debug.Log(transform.localRotation);
        Debug.Log(transform.eulerAngles);
        Debug.Log(transform.localEulerAngles);
        // 获取缩放
        Debug.Log(transform.localScale);
        // 向量
        Debug.Log(transform.forward);// z轴
        Debug.Log(transform.right);// x轴
        Debug.Log(transform.up);// y轴
    }

    // Update is called once per frame
    void Update() {
        // 时时刻刻看向0,0,0这个点,z轴看向
        transform.LookAt(Vector3.zero);
        // 旋转
        transform.Rotate(Vector3.up,10);// 每一帧 绕y轴旋转10度
        // 绕某个物体旋转
        transform.RotateAround(Vector3.zero, Vector3.up, 5);// 每一帧 绕着0,0,0点,up轴旋转5度
        // 移动
        transform.Translate(Vector3.forward * 0.1f);// // 每一帧 向前方移动0.1
    }
}

Transform处理父子关系
image.png

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

public class TransformTest : MonoBehaviour {
    // Start is called before the first frame update
    void Start() {
        // 父子关系
        // 获取父物体 transform.parent.gameObject
        // 获取子物体(不只一个)的个数
        Debug.Log(transform.childCount);
        // 解除与子物体的关系
        transform.DetachChildren();
        // 获取子物体
        Transform trans = transform.Find("Child"); // "Child" 为某一个要查找的子物体的名称
        trans = transform.GetChild(0); // 根据子物体中的索引来找
        // 判断一个物体是不是另外一个物体的子物体
        bool res=trans.IsChildOf(transform); // 判断trans是不是transform的子物体
        Debug.Log(res);
        // 设置为父物体
        trans.SetParent(transform);
    }

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

PC端-键盘鼠标操作 Input

鼠标使用

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

public class KeyboradTest : MonoBehaviour {
    // Start is called before the first frame update
    void Start() {

    }

    // Update is called once per frame
    void Update() {
        // 鼠标的点击
        // 按下鼠标 0左键 1右键 2滚轮
        if(Input.GetMouseButtonDown(0)) {
            Debug.Log("按下鼠标左键了");
        }
        // 持续按下鼠标
        if (Input.GetMouseButton(0)) {
            Debug.Log("持续按下鼠标左键");
        }
        // 抬起鼠标
        if(Input.GetMouseButtonUp(0)) {
            Debug.Log("抬起鼠标左键了");
        }
    }
}

键盘使用

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

public class KeyboradTest : MonoBehaviour {
    // Start is called before the first frame update
    void Start() {

    }

    // Update is called once per frame
    void Update() {
        // 按下键盘按键
        if(Input.GetKeyDown(KeyCode.A)) {
            Debug.Log("按下了A");
        }
        // 持续键盘按键 大写A报错,小写a正确
        if (Input.GetKey("a")) {
            Debug.Log("持续按下了A");
        }
        // 抬起键盘按键
        if (Input.GetKeyUp(KeyCode.A)) {
            Debug.Log("抬起了A");
        }
    }
}

虚拟轴 虚拟按键

虚拟轴是一个数值在-1~1内的数轴,最重要的就是-1、0、1。
image.png

解决什么问题?
解决游戏在不同平台上的操作兼容问题。比如:电脑上有键盘操作,而Switch上没有键盘。
所以让游戏代码中控制虚拟轴,虚拟轴在不同平台上进行相应的控制。

设置
(1)选择左上角的“编辑”
(2)选择“项目设置”
(3)看到“输入管理器”
(4)image.png

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

public class AxisTest : MonoBehaviour {
    // Start is called before the first frame update
    void Start() {

    }

    // Update is called once per frame
    void Update() {
        // 获取水平轴
        float horizontal = Input.GetAxis("Horizontal");// Horizontal为水平轴的名称,在项目设置查询或修改。
        // 获取垂直轴
        float vertical = Input.GetAxis("Vertical");
        Debug.Log(horizontal+"  "+vertical);

        // 虚拟按键
        if (Input.GetButtonDown("Jump")) { // Jump还是在项目设置查询或修改
            Debug.Log("空格按下");
        }
        if (Input.GetButton("Jump")) {
            Debug.Log("空格持续按下");
        }
        if (Input.GetButtonUp("Jump")) {
            Debug.Log("空格抬起");
        }
    }
}

手机平板-触摸操作

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

public class TouchTest : MonoBehaviour {
    // Start is called before the first frame update
    void Start() {
        // 开启多点触摸
        Input.multiTouchEnabled = true;
    }

    // Update is called once per frame
    void Update() {
        // 判断单点触摸
        if (Input.touchCount == 1) {
            // 触摸对象
            Touch touch = Input.touches[0];
            // 触摸位置
            Debug.Log(touch.position);
            // 触摸阶段
            switch (touch.phase) {
                case TouchPhase.Began:
                    break;
                case TouchPhase.Moved:
                    break;
                case TouchPhase.Stationary:
                    break;
                case TouchPhase.Ended:
                    break;
                case TouchPhase.Canceled:
                    break;
            }
        }

        // 判断多点触摸
        if(Input.touchCount == 2) {
            Touch touch1 = Input.touches[0];
            Touch touch2 = Input.touches[1];
            // 触摸位置
            Debug.Log(touch1.position);
            // 触摸阶段
            switch (touch1.phase) {
                case TouchPhase.Began:
                    break;
                case TouchPhase.Moved:
                    break;
                case TouchPhase.Stationary:
                    break;
                case TouchPhase.Ended:
                    break;
                case TouchPhase.Canceled:
                    break;
            }
            // 触摸位置
            Debug.Log(touch2.position);
            // 触摸阶段
            switch (touch2.phase) {
                case TouchPhase.Began:
                    break;
                case TouchPhase.Moved:
                    break;
                case TouchPhase.Stationary:
                    break;
                case TouchPhase.Ended:
                    break;
                case TouchPhase.Canceled:
                    break;
            }
        }
    }
}

音乐添加 AudioClip AudioSource

直接添加

摄像机上记得勾选 image.png

在物体对象中添加组件 Audio Source,里面进行相关设置 image.png

示例脚本

image.pngimage.png

视频播放 VideoPlayer VideoClip

在要播放的物体中,添加 Video Player 组件。
image.png
简单操作:
image.png

脚本编写与音乐播放类似

角色控制器 CharacterController

为游戏物体添加 CharacterController 组件
image.png

示例脚本
image.png

为物体添加重力

为游戏物体添加 Rigidbody 组件
image.png

碰撞器 Colliding

产生条件:(1)碰撞的2个物体必须有碰撞器(2)其中至少一个有刚体(Rigidbody)

三个方法:
(1)OnCollisionEnter 监听发生碰撞,只执行一次
(2)OnCollisionStay 持续碰撞(3)OnCollisionExit 结束碰撞时

脚本作用:火焰碰撞到平面,火焰消失,产生爆炸效果,过一秒后,爆炸效果也消失
(1)把这个火焰脚本放到火焰那个游戏物体中
image.png
**(2)把下面的脚本放到爆炸图那个游戏物体中,就在项目Assets中的图片直接设置 **——过1秒就会自动销毁自身
image.png
这个示例说明,每个脚本作用放到自身要作用的游戏物体身上,不要弄复杂。一个脚本一个作用。

触发器

在给物体添加刚体组件,其中有个 ”是触发器“ 选项,选择勾选,这样就变成触发器了。

image.png

image.png

特殊的物理关节

铰链

image.png

弹簧

image.png

固定关节

image.png

物理材质的影响

image.png

游戏中的红外线,射线检测

image.png
image.png

posted @ 2023-05-29 21:31  不爱菠萝的菠萝君  阅读(161)  评论(0)    收藏  举报