【Unity】RPG小游戏创建游戏中的交互

RPG小游戏创建游戏中的交互

创建可交互的物体的公共的父类(Interactable)

InteractableObject 类

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

/// <summary>
/// NPC和Pickable的父类
/// </summary>

public class InteractableObject : MonoBehaviour
{
    private NavMeshAgent playerAgent;
    private bool haveInteeacted;标志位(是否进行交互过,默认每次点击只交互一次)
    public void OnClick(NavMeshAgent playerAgent)//将 NavMeshAgent 组件传递过来。
    {
        this.playerAgent = playerAgent;
        playerAgent.stoppingDistance = 2;与被交互的物体设置的边距(保证不穿模)。
        playerAgent.SetDestination(transform.position);//设置目标位置让其移到附近。
        haveInteeacted = false;//添加上这个便可以将面板再次显示。
    }

    private void Update()
    {
        if(playerAgent != null && haveInteeacted == false && playerAgent .pathPending==false)
        {
            if(playerAgent.remainingDistance<=2)//到达目标位置才进行交互。
            {
                Interact();//交互
                haveInteeacted = true;
            }
        }
    }
    protected virtual void Interact()
    {
        print("Interacting with Interactable Object.");
    }
}

NPCObject 类

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 定义NPC
/// </summary>

public class NPCObject : InteractableObject//继承自InteractableObject
{
    public new string name;
    //public string Name {  get; set; }

    public string[] contentList;

    //public DialogueUI dialogueUI;
    protected override void Interact()
    {
        //dialogueUI.Show(name, contentList);
        DialogueUI.Instance.Show(name, contentList);
    }
}

PickableObject 类

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 定义Pickable的动作
/// </summary>

public class PickableObject : InteractableObject
{
    public ItemScriptObject itemSO;//用来表示哪个Item

    protected override void Interact()
    {
        Destroy(this.gameObject);
        InventoryManager.Instance.AddItem(itemSO); 
    }
}
相关推荐
没什么本事18 小时前
关于C# panel 添加lable问题 -- 明确X和Y 位置错误
android·java·c#
火星papa19 小时前
C# 实现平滑流畅的进度条ProgressBar
c#·进度条·progressbar·平滑流畅
游乐码21 小时前
UnityGUI(五)GUI控件综合使用
开发语言·unity·c#
程序leo源21 小时前
C语言知识总结
c语言·开发语言·c++·经验分享·笔记·青少年编程·c#
LF男男21 小时前
TshitBullect.cs
unity
烛阴1 天前
TEngine 入门系列(二):三件套环境搭建 -- Unity + TEngine + AI 助手
前端·c#·unity3d
皮皮虾12341 天前
诛仙手游多开最多几开?用什么云手机比较好?
游戏·智能手机
资源分享助手1 天前
三网H5小游戏夜市餐厅搭建教程、H5游戏服务端、Win服务端部署
游戏
码农阿豪1 天前
Docker 部署 XiuXianGame 文字修仙游戏:极空间 NAS 上随时挂机刷资源
游戏·docker·容器
谙弆悕博士1 天前
【附C语言源码】从零实现命令行贪吃蛇游戏
c语言·开发语言·学习·游戏·游戏程序·小游戏·贪吃蛇