Unity C#代碼入門
1. 腳本基本結構
1.1 unity生成的模板
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//設置初始值,相當於構造函數
}
// Update is called once per frame
void Update()
{
//不停循環執行的代碼
}
}
1.2 常用的注解屬性
[SerializeField]
float moveSpeed = 8;
Debug.Log("Celling");//控制台輸出
other.gameObject.tag == "Celling"//獲得tag
csharp如果不標明類別, 默認pravite
加上SerializeField, 能讓pravite的變量, 在unity右側直接調節
Time.deltaTime
不同的機器, 游戲幀數不同, Time.deltaTime可以讓機器用相同的幀數執行
1.3 常見的類
類名 | 解釋 |
---|---|
Text | 得到UI的text(需要導入using UnityEngine.UI;) |
Animator | 動畫 |
SpriteRenderer | 渲染器(改變物體的外觀?) |
GameObject | 獲取游戲內物體 |
2. 源碼解析
public class Player : MonoBehaviour
{
//類名必須一致
}
2.1 初始值定義
void Start()
{
HP = 10;
score = 0;
scoreTime = 0f;
anim = GetComponent<Animator>();
render = GetComponent<SpriteRenderer>();
deathSound = GetComponent<AudioSource>();
}
GetComponent
2.2 循環執行函數
void Update()
{
if (Input.GetKey(KeyCode.RightArrow))
{
transform.Translate(moveSpeed * Time.deltaTime, 0, 0);
render.flipX = false;
anim.SetBool("run", true);
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
transform.Translate(-moveSpeed * Time.deltaTime, 0, 0);
render.flipX = true;
anim.SetBool("run", true);
}
else
{
anim.SetBool("run", false);
}
UpdateScore();
}
2.2.1 鍵盤監聽函數
Input.GetKey(KeyCode.RightArrow) //輸入的是右邊箭頭
2.2.2 變換屬性 transform
transform.Translate(moveSpeed * Time.deltaTime, 0, 0);
將向x軸移動一定的距離
其實就是右側的這些屬性, 因此Rotation旋轉, Scale縮放都能調整
render.flipX = false;
GetComponent<SpriteRenderer>().flipX = false;
同理:
anim.SetBool("run", true);
GetComponent<Animator>().SetBool("run", true);
動畫也是如此
當然動畫要復雜些
2.3 碰撞函數
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Normal")
{
if (other.contacts[0].normal == new Vector2(0f, 1f))
{
currentFloor = other.gameObject;
ModifyHp(1);
other.gameObject.GetComponent<AudioSource>().Play();
Debug.Log("floor1");
}
}
else if (other.gameObject.tag == "Nails")
{
if (other.contacts[0].normal == new Vector2(0f, 1f))
{
currentFloor = other.gameObject;
ModifyHp(-2);
Debug.Log("floor2");
anim.SetTrigger("hurt");
other.gameObject.GetComponent<AudioSource>().Play();
}
}
else if (other.gameObject.tag == "Celling")
{
if (other.contacts[0].normal == new Vector2(0f, -1f))
{
currentFloor.GetComponent<BoxCollider2D>().enabled = false;
ModifyHp(-2);
Debug.Log("Celling");
anim.SetTrigger("hurt");
other.gameObject.GetComponent<AudioSource>().Play();
}
}
}
所謂碰撞就是, 遇到other這個物體會和它發生物理效果, 而不是穿過
2.3.1 碰撞檢測精確到邊
other.contacts[0].normal == new Vector2(0f, 1f)
//normal就是法向量
2.4 穿過函數
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "DeadLine")
{
ModifyHp(-12);
Die();
}
}
2.5 操作子組件
void UpdateHpBar()
{
for (int i = 0; i < HpBar.transform.childCount; i++)
{
if (HP > i)
{
HpBar.transform.GetChild(i).gameObject.SetActive(true);
}
else
{
HpBar.transform.GetChild(i).gameObject.SetActive(false);
}
}
}
主要是對gameObject的操作
3. 常用函數
3.1 結束游戲
void Die()
{
deathSound.Play();
Time.timeScale = 0f; //時間靜止
btnReplay.SetActive(true);
}
3.2 重啟游戲
//需要使用以下命名空間
using UnityEngine.SceneManagement;
public void Replay()
{
Time.timeScale = 1;
/*重新加載場景*/
SceneManager.LoadScene("SampleScene");
}
3.3 銷毀物體
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Floor : MonoBehaviour
{
[SerializeField] float moveSpeed = 1f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(0,moveSpeed * Time.deltaTime,0);
if(transform.position.y>=4.7f)
{
Destroy(gameObject);
transform.parent.GetComponent<FloorManager>().SpwanFloor();
}
}
}
3.4 生成新的物體
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FloorManager : MonoBehaviour
{
[SerializeField] GameObject[] floorPerfabs;
public void SpwanFloor()
{
int r = Random.Range(0,2);
GameObject floor = Instantiate(floorPerfabs[r],transform);
floor.transform.position = new Vector3(Random.Range(-3.8f,3.8f),-5,0);
}
}