# unity 中基本类的使用
- 场景切换
row 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51void Start()
{
// 场景跳转
SceneManager.LoadScene(1);
// 获取当前场景
Scene scene = SceneManager.GetActiveScene();
// 场景名称
Debug.Log(scene.name);
// 是否已加载
Debug.Log(scene.isLoaded);
//路径
Debug.Log(scene.path);
//索引
Debug.Log(scene.buildIndex);
GameObject[] gmo = scene.GetRootGameObjects();
Debug.Log(gmo.Length);
//场景管理类
SceneManager.CreateScene("newScene");
//已加载场景个数
Debug.Log(SceneManager.sceneCount);
//卸载
SceneManager.UnloadSceneAsync("newScene");
//加载场景 但是如果场景大的话容易卡顿
SceneManager.LoadScene("SampleScene",LoadSceneMode.Additive);
}
- 异步加载
row 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41public class AsyncTest : MonoBehaviour
{
AsyncOperation operation;
// Start is called before the first frame update
void Start()
{
}
// 协程方法用来加载异步场景
IEnumerator loadScene(){
operation = SceneManager.LoadSceneAsync(1);
yield return operation;
}
// Update is called once per frame
void Update()
{
Debug.Log(operation.progress);
}
}
- transform
row 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46void Start()
{
//位置 && 角度
Debug.Log(transform.position);
Debug.Log(transform.rotation);
Debug.Log(transform.localPosition);
Debug.Log(transform.localRotation);
//欧拉角
Debug.Log(transform.localEulerAngles);
Debug.Log(transform.eulerAngles);
//缩放
Debug.Log(transform.localScale);
//向量
Debug.Log(transform.forward);
Debug.Log(transform.right);
Debug.Log(transform.up);
//父子关系
//获取父物体
Debug.Log(transform.parent.gameObject);
//子物体个数
Debug.Log(transform.childCount);
//解除父子关系
transform.DetachChildren();
//获取子物体
Transform tra = transform.Find("test");
tra = transform.GetChild(0);
bool res = tra.IsChildOf(transform);
Debug.Log(res);
//设置父物体
tra.SetParent(transform);
}
// Update is called once per frame
void Update()
{
//看向某个点
transform.LookAt(Vector3.zero);
//旋转
transform.Rotate(Vector3.up, 1);
//绕某个物体旋转
transform.RotateAround(Vector3.zero, Vector3.up, 5);
//移动
transform.Translate(Vector3.forward * 0.1f);
}
鼠标键盘
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33//鼠标
if (Input.GetMouseButtonDown(0))
{
Debug.Log("按下了左键");
}
else if (Input.GetMouseButtonDown(1))
{
Debug.Log("右键");
}
//持续按下
if (Input.GetMouseButton(0))
{
Debug.Log("持续");
}
//抬起鼠标
if (Input.GetMouseButtonUp(0))
{
Debug.Log("抬起");
}
//键盘按下
if(Input.GetKeyDown(KeyCode.A))
{
Debug.Log("A");
}
//持续
if (Input.GetKey(KeyCode.S)) {
Debug.Log("S");
}
//抬起
if (Input.GetKeyUp(KeyCode.D)) {
Debug.Log("d抬起");
}声明变量时可以使用
row 1
[private float moveSpeed; ]
可以保护类以确定类只在内部使用,同时通过[SerializeField]
将其暴露再 Inspector 中,避免频繁调试代码