【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); 
    }
}
相关推荐
唐青枫3 小时前
别把日志、权限写进业务方法:C#.NET 动态代理从原理到实战
c#·.net
fujisheng6614 小时前
Unity UI 生命周期状态机:处理 Covered、异步竞态与事务回滚
c#·unity3d
yyt3630458415 小时前
KLineChartQuant:GLSL 的精度问题及 RTC 解法
前端·vue.js·react.js·交互·图形渲染·webgl·数据可视化
Dream-Y.ocean7 小时前
基于具身交互智能数字人,我用Flask搭了一个AI教学平台:课代表AI全流程实战
人工智能·flask·交互
励志不掉头发的内向程序员8 小时前
【LibreCAD 2D架构】从鼠标点击到图形创建:RS_ActionDrawLine交互流程与状态机解析
开发语言·c++·qt·学习·系统架构·计算机外设·交互
Htr_9 小时前
Reflexio 使用指南:让 AI 智能体从每次交互中持续学习
人工智能·学习·交互
leoZ2319 小时前
第 8 篇:与 AI 协作的工作流 + 完整案例
前端·人工智能·神经网络·自然语言处理·性能优化·c#·php
fujisheng66111 小时前
Unity 异步 UI 实战:取消令牌、版本校验与旧句柄隔离
c#·unity3d
额鹅恶饿呃12 小时前
随着CentOS官方停服的时间越来越久,大量仍在使用CentOS7的企业和运维从业者
java·python·算法·c#·ruby
乌药ice12 小时前
c#中一个多线程安全的HashSet
开发语言·c#