【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); 
    }
}
相关推荐
半夢半醒116 分钟前
[原创]《C#高级GDI+实战:从零开发一个流程图》第章:增加菱形、平行四边形、圆角矩形,文本居中显示
算法·c#·流程图
蓝斯4973 小时前
C# 调用邮箱应用发送带附件的邮件
网络·c#·github
BuHuaX4 小时前
U3D抖微小游戏开发流程 (一)
unity·c#·游戏引擎·游戏策划
脚踏实地皮皮晨4 小时前
003003002_WPF Grid 基类官方类定义逐行深度解析
开发语言·windows·算法·c#·wpf·visual studio
_ZHOURUI_H_13 小时前
Unity MyFramework 用法说明(二十三):使用 PrefabPoolManager 复用预设实例
unity·游戏引擎·游戏开发·游戏ui·手游开发
凯丨15 小时前
AI 蠕虫来了:恶意文档如何通过 Copilot for Word 自我传播?
人工智能·c#·copilot
冰凌糕15 小时前
Unity3D Shader 法线与基础光照
unity
Aaron - Wistron15 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
骊城英雄17 小时前
基于C#+avalonia ui实现的跨平台点胶机灌胶监控控制上位机软件
开发语言·ui·c#