【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); 
    }
}
相关推荐
song5012 小时前
Ascend C 算子开发:从入门到上手
c语言·开发语言·图像处理·人工智能·分布式·flutter·交互
玄米乌龙茶1234 小时前
LLM成长笔记(十三):系统设计与项目实战
笔记·unity·游戏引擎
baivfhpwxf20235 小时前
c# 中对像之间频繁的转换会慢吗?
开发语言·c#
加号36 小时前
【C#】 实现 XRC 异或冗余校验:原理与实践
c#·xrc
小钻风33667 小时前
Java + Spring Boot 操作 Kafka 完整学习指南
c#·linq
叫我少年7 小时前
C# 程序的常规结构 — 命名空间、类型、入口点与表达式
c#
重生之我是Java开发战士9 小时前
【贪心算法】最长回文串,增减字符串匹配,分发饼干,最优除法,跳跃游戏
游戏·贪心算法·哈希算法
ZC跨境爬虫9 小时前
跟着 MDN 学CSS day_12 :(值与单位的技能测试与深入理解)
前端·javascript·css·ui·交互
sheeta199811 小时前
LeetCode 每日一题笔记 日期:2026.05.24 题目:1340. 跳跃游戏 V
笔记·leetcode·游戏
_Evan_Yao11 小时前
游戏和编程两不误:用Unity做一个简单小游戏
后端·游戏·unity·游戏引擎