角色互动加分显示的实现
思路:在角色的脚本里对应该加分的地方用变量统计分数,同时再创建一个ui对象,然后用委派事件获取角色的得分。
在角色的脚本里设置分数
//基础分数
public int stepPoint;
//总共得到了多少分数
private int pointResult;
//角色互动加分的函数
public void Jump(InputAction.CallbackContext context)
{
//如果角色短跳触发成功,加分
if (dir == Direction.Up && context.performed && !isJump)
{
pointResult += stepPoint;
}
}
布置页面以及编译对应的脚本
页面如下:
创建个新的脚本挂载到Canvas Text里:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UiManager : MonoBehaviour
{
public Text screenText;
void Start()
{
screenText.text = "0";
}
}
把之前创建的文字丢进去。
显示数字的控制也完成了!
使用事件委托将两者连接
创建委托脚本:
扫描二维码关注公众号,回复:
14913034 查看本文章
脚本如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class EventHander : MonoBehaviour
{
//委托的事件
public static event Action<int> GetPointEvent;
//触发委托事件的函数
public static void CallGetPointEvent (int point)
{
//如果委托有接收方就提醒他委托开始,并且把值给他
GetPointEvent ? .Invoke(point);
}
}
青蛙(玩家控制)需要建立委托:
//基础分数
public int stepPoint;
//总共得到了多少分数
private int pointResult;
//角色互动加分的函数
public void Jump(InputAction.CallbackContext context)
{
//如果角色短跳触发成功,加分
if (dir == Direction.Up && context.performed && !isJump)
{
pointResult += stepPoint;
EventHander.CallGetPointEvent(pointResult); //发起委托
}
}
界面部分接收委托:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UiManager : MonoBehaviour
{
public Text scoreText;
void Start()
{
screenText.text = "0";
}
//脚本刚被调用时使用
private void OnEnable()
{
//注册
EventHander.GetPointEvent += OnGetPointEvent;
}
//脚本不再被使用
private void OnDisable()
{
}
///<summary>
///接收委托传来的值
///</summary>
private void OnGetPointEvent(int point)
{
//把传过来的值显示在屏幕
scoreText.text = point.ToString();
}
}
完成!