https://learn.u3d.cn/tutorial/beginner-gameplay-scripting
Update(不是按固定時間呼叫的) 經常用於
FixedUpdate(呼叫時間間隔相同)
使用 IDE 的 Unity Event Functions 插入函數
void Start ()
{
//值型別變數
Vector3 pos = transform.position; // 值拷貝
pos = new Vector3(0, 2, 0);
//參照型別變數
Transform tran = transform;
tran.position = new Vector3(0, 2, 0);
}
Instantiate 用於動態生成預製體物件(建立預製件的克隆體)
⭐動態範例化生成的子彈預製體節點被強制轉型成了 RigidBody
public Rigidbody bulletPrefab; // 可以不是GameObject而是繫結的元件
public Transform firePosition;
public float bulletSpeed;
...
Rigidbody bulletInstance = Instantiate(bulletPrefab, firePosition.position, firePosition.rotation) as Rigidbody;
案例中用到了 as 關鍵字。《C# 8.0本質論》裡沒有寫
使用 FindGameObjectsWithTag 初始化查詢所有 Tag 為 Player 的節點儲存至陣列中
C# 陣列是從抽象的基本類型Array派生的參照型別
public GameObject[] players;
void Start()
{
players = GameObject.FindGameObjectsWithTag("Player");
foreach (var player in players)
{
Debug.Log($"{player.name}");
}
}
其他內容以前筆記有寫,略過
用整數描述方向不易讀,可以建立 enum 型別(類內類外都可建立)
enum Direction : short
{
North, // 0
East, // 1
South = 100, // 100
West // 101
};
void Start()
{
Direction myDirection;
myDirection = Direction.North;
var newDirection = ReverseDirection(myDirection);
}
Direction ReverseDirection (Direction dir)
{
if(dir == Direction.North)
dir = Direction.South;
else if(dir == Direction.South)
dir = Direction.North;
else if(dir == Direction.East)
dir = Direction.West;
else if(dir == Direction.West)
dir = Direction.East;
return dir;
}
跟 C++ 差不多
public int intelligence = 5;
void Start()
{
switch (intelligence)
{
case 1:
break;
case 2:
break;
default:
break;
}
}