接下來要寫程式來改變分數
1.創建一個新的腳本
2.新建一個新物件
hierary → create empty → 取名叫UI → 把剛剛的腳本拉過來
3.輸入程式碼
using UnityEngine;
using TMPro;
public class GameUI : MonoBehaviour
{
public TMP_Text scoreText;
void Start()
{
}
void Update()
{
}
}
回到unity,把Score拉到UI新建的變數
再把Snack的腳本改成這樣:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
public class Snack : MonoBehaviour
{
public GameUI gameUI;
Vector3 direction;
public float speed;
public Transform bodyPrefab;
public List<Transform> bodies = new List<Transform>();
void Start()
{
Time.timeScale = speed;
ResetStage();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
Debug.Log("W");
direction = Vector3.up;
}
if (Input.GetKeyDown(KeyCode.A))
{
Debug.Log("A");
direction = Vector3.left;
}
if (Input.GetKeyDown(KeyCode.S))
{
Debug.Log("S");
direction = Vector3.down;
}
if (Input.GetKeyDown(KeyCode.D))
{
Debug.Log("D");
direction = Vector3.right;
}
}
private void FixedUpdate()
{
for(int i = bodies.Count - 1; i > 0; i--)
{
bodies[i].position = bodies[i - 1].position;
}
transform.Translate(direction);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Food"))
{
bodies.Add(Instantiate(bodyPrefab
, transform.position
, Quaternion.identity));
gameUI.AddScore();
}
if (collision.CompareTag("Obstacle"))
{
Debug.Log("game over!");
ResetStage();
}
}
void ResetStage()
{
transform.position = Vector3.zero;
direction = Vector3.zero;
for (int i = 1; i < bodies.Count; i++)
{
Destroy(bodies[i].gameObject);
}
bodies.Clear();
bodies.Add(transform);
gameUI.ResetScore();
}
}
GameUI的程式碼:
using UnityEngine;
using TMPro;
public class GameUI : MonoBehaviour
{
public TMP_Text scoreText;
int score;
void Start()
{
}
void Update()
{
}
public void ResetScore()
{
score = 0;
scoreText.text = score.ToString();
}
public void AddScore()
{
score++;
scoreText.text = score.ToString();
}
}
然後snack裡面的GameUI變數要把UI拉過來