【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); 
    }
}
相关推荐
勿忘初心912 小时前
游戏手柄遥控越疆协作机器人[四]
游戏·机器人
·心猿意码·4 小时前
C# 垃圾回收机制深度解析
开发语言·c#
招风的黑耳4 小时前
500+带交互的元件库:Axure原型设计的活字典
交互·axure·原型
AI 研究所4 小时前
1024开发者节:开源发布,引领生态繁荣
人工智能·语言模型·开源·大模型·交互·agent
唐青枫4 小时前
C#.NET 开发必备:常用特性与注解用法大全
c#·.net
视觉AI9 小时前
HTTP 请求与数据交互全景指南:Request、GET、POST、JSON 及 curl
http·json·交互
2501_9400940211 小时前
NDS模拟器安卓版 melonDS模拟器 汉化中文版 NDS BIOS和固件+NDS游戏和详细的使用教程
android·游戏
好望角雾眠15 小时前
第四阶段C#通讯开发-5:TCP
网络·笔记·网络协议·tcp/ip·c#
InCerry15 小时前
.NET周刊【11月第1期 2025-11-02】
c#·.net周报·.net周刊