【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); 
    }
}
相关推荐
靓仔建9 分钟前
在.NET Framework 4.7.2 使用Microsoft.Practices.EnterpriseLibrary.Data配置出错
c#·.net
MonkeyBananas36 分钟前
C#项目引用log4net日志服务
c#
专注VB编程开发20年42 分钟前
C# int*指向 int 的指针类型(unsafe 上下文)
java·开发语言·c#
凯子坚持 c1 小时前
深度解析 MySQL 与 MCP 集成:从环境构建到 AI 驱动的数据交互全流程
人工智能·mysql·交互
Eiceblue1 小时前
通过 C# 将 RTF 文档转换为图片
开发语言·算法·c#
yuegu7772 小时前
Electron for鸿蒙PC实战项目之麻将游戏
游戏·electron·harmonyos
c#上位机2 小时前
halcon求图像灰度最大值和最小值——min_max_gray
图像处理·人工智能·计算机视觉·c#·上位机·halcon
sali-tec11 小时前
C# 基于halcon的视觉工作流-章66 四目匹配
开发语言·人工智能·数码相机·算法·计算机视觉·c#
搬砖的青蛙12 小时前
游戏运行库整合包,可避免99%游戏启动问题,支持xp-11系统
游戏·运行库·xp-11
氤氲息17 小时前
鸿蒙 ArkTs 的WebView如何与JS交互
javascript·交互·harmonyos