1.创建Cube物体,然后是CubeScore,CubeScore只有GUI Text组件,作用是显示记数文字
2.创建Gold物体,然后是GoldScore
3.创建Player物体,我这里直接用的Sphere
4.在Sphere里添加MoveEat脚本,在碰撞Cube物体后销毁Cube,并生成金币
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveEat : MonoBehaviour {
private Transform m_transform; //定义位置对象
private GUIText m_guitext; //定义一个GUIText类型对象m_guitext
private int i = 0; //定义整型变量i,赋初值为0,i的作用是对销毁Cube进行记数
public GameObject m_gold; //定义公共对象m_gold,然后在Unity里的MoveEat脚本组件里拖拽Gold物体到对应那一栏
void Start () {
m_transform = gameObject.GetComponent<Transform>(); //获取游戏对象位置组件
m_guitext = GameObject.Find("CubeScore").GetComponent<GUIText>(); //获取CubeScore游戏对象的GUIText组件
}
void Update () { //对此脚本依附物体进行位移操作
if (Input.GetKey(KeyCode.A)) {
m_transform.Translate(Vector3.left * 5 * Time.deltaTime,Space.World);
}
if (Input.GetKey(KeyCode.D))
{
m_transform.Translate(Vector3.right * 5 * Time.deltaTime,Space.World);
}
if (Input.GetKey(KeyCode.W))
{
m_transform.Translate(Vector3.forward * 5 * Time.deltaTime,Space.World);
}
if (Input.GetKey(KeyCode.S))
{
m_transform.Translate(Vector3.back * 5 * Time.deltaTime,Space.World);
}
}
void OnCollisionEnter(Collision other) //当进入碰撞体时
{
if (other.gameObject.tag == "cube") //如果进入的是标签为Cube的物体时
{
i++; //i的自增
m_guitext.text = "打破Cube数:" + i; //对CubeScore游戏对象的GUIText组件的text属性进行修改
Instantiate(m_gold, other.gameObject.GetComponent<Transform>().position, Quaternion.identity); //在物体位置实例化Gold物体,就是克隆金币(Quaternion.identity无旋转)
Destroy(other.gameObject); //销毁被碰撞体
}
}
void OnTriggerEnter(Collider other) //当进入触发器
{
if (other.gameObject.tag == "gold") //如果进入的是标签为gold(本体金币为gold标签,克隆体也为gold标签)
{
other.gameObject.SendMessage("addGoldScore"); //发送信息addGoldScore(addGoldScore是自定义函数,位置在Gold脚本,Gold脚本依附在Gold物体上)
Destroy(other.gameObject); //销毁被触发器
}
}
}
5.Cube直接被销毁并记数,但是GoldScore是用发送信息的方式,所以在Gold物体里要添加接收脚本,Gold里的这个脚本只是记数显示脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gold : MonoBehaviour {
private Transform m_transform;
private static int i=0; //注意这里需要静态变量
private GUIText m_goldscoretext;
// Use this for initialization
void Start () {
m_transform = gameObject.GetComponent<Transform>();
m_goldscoretext= GameObject.Find("GoldScore").GetComponent<GUIText>();
}
// Update is called once per frame
void Update () {
}
public void addGoldScore() {
i++;
m_goldscoretext.text = "拾取金币数:" + i;
}
}
本文介绍如何在Unity中使用C#脚本来实现一个简单的游戏计分系统,包括通过碰撞销毁方块来增加分数并生成金币,以及收集金币进一步加分的机制。
2万+

被折叠的 条评论
为什么被折叠?



