之前一直在听别人说面向对象,自己也一直在说对象,其实在心里对面向对象并没有什么感觉,知道今天在写一个人物对话的功能,突然就明白了对象的意思,就像突然顿悟了一样,对象就是每一个类只管它自己的事情,不要和别的功能重叠,不要和别的功能重叠,不要和别的功能重叠。
以下是详细代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PeopleDialogController : MonoBehaviour
{
[Tooltip("相距多少米可以说话")]
public float range = 10;
public LayerMask layerMask = 0;
public Transform dialog = null;
/// <summary>
/// 交谈内容
/// </summary>
public List<string> chatList = new List<string>();
private Text dialogcontent = null;
private Button confirmBtn = null;
private bool isCanTalk = false;
private int dialogIndex = 0;
// Use this for initialization
void Start()
{
if (dialog != null)
{
dialogcontent = dialog.Find<Text>("contentTxt");
confirmBtn = dialog.Find<Button>("confirmBtn");
}
if (confirmBtn != null)
{
confirmBtn.onClick.AddListener(ClickConfirmMethod);
}
}
// Update is called once per frame
void Update()
{
DetectPlayerMethod();
ShowDialogMethod();
}
/// <summary>
/// 检测是否可以显示对话框
/// 周围给定范围内有玩家的话就可以对话
/// </summary>
private void DetectPlayerMethod()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, range, layerMask);
if (colliders.Length > 0)
{
isCanTalk = true;
}
else
{
isCanTalk = false;
}
}
/// <summary>
/// 显示对话框
/// </summary>
private void ShowDialogMethod()
{
if (isCanTalk)
{
if (Input.GetKeyDown(KeyCode.E))
{
if (!dialog.gameObject.activeSelf)
{
dialogcontent.text = chatList[0].Trim();
dialog.Show();
}
else
{
ClickConfirmMethod();
}
}
}
else
{
dialogIndex = 0;
dialog.Hide();
}
}
/// <summary>
/// 点击对话框里的确定按钮
/// </summary>
private void ClickConfirmMethod()
{
dialogIndex++;
if (dialogIndex < chatList.Count)
{
dialogcontent.text = chatList[dialogIndex].Trim();
}
else
{
dialog.Hide();
dialogIndex = 0;
WaiJingManager.Instance.GetProofMethod(transform.name);
this.enabled = false;
}
}
}