【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); 
    }
}
相关推荐
技术小甜甜8 小时前
[软件商业化] Steam 游戏更新怎么发公告?预告、上传新包和正式升级说明的顺序怎么安排?
游戏·steam·独立游戏·steamworks·游戏更新·软件商业化
F20226974869 小时前
西门子 PLC 与 C# 通信
开发语言·c#
吴可可12314 小时前
C#实现CAD框选闭合图元外偏移1毫米
c#
꒰ঌ 安卓开发໒꒱14 小时前
.NET CAP入门到入土
后端·c#·.net
逝水无殇18 小时前
C# 枚举(Enum)详解
开发语言·后端·c#
最爱老式锅包肉19 小时前
《HarmonyOS技术精讲-ArkGraphics 2D(方舟2D图形服务)》第七篇:动效来袭——与ArkUI结合实现2D动画与交互
华为·交互·harmonyos
澹然疏离19 小时前
HarmonyOS应用《民族图鉴》开发第28篇:AI对话页——智能问答交互
交互·harmonyos
Java面试题总结20 小时前
C# 源生成器使用方法
windows·ui·c#
影寂ldy20 小时前
C# WinForms 窗体继承
开发语言·c#