【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); 
    }
}
相关推荐
Jiamiren12 分钟前
WEEX Labs 周度观察:AI 基础设施的“权力游戏”与硬核变现时代
人工智能·游戏
影寂ldy35 分钟前
C# Task 进阶:WaitAll / WaitAny / WhenAll / WhenAny
开发语言·c#
o5278831842 小时前
校园一体化管理系统2.1、基于整洁四层架构 + DDD+CQRS 项目目录解读
后端·架构·c#·asp.net·visual studio
YakSue15 小时前
游戏项目中的程序化生成(PCG):五层工作的耦合问题
游戏
农村小镇哥19 小时前
C#中的字符串格式化
服务器·开发语言·c#
weixin_4242946719 小时前
Unity的测试Edit Mode和Play Mode,有什么区别?
unity
国际学术会议-杨老师20 小时前
2026年游戏美学、动画生成与色彩科学国际会议(GEAAC 2026)
游戏·动画·色彩科学
工业HMI实战笔记21 小时前
【无标题】
大数据·人工智能·ui·自动化·人机交互·交互
qizayaoshuap1 天前
# [特殊字符] 猜数字 — 鸿蒙ArkTS游戏逻辑与交互反馈系统设计
游戏·华为·harmonyos