【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); 
    }
}
相关推荐
CoderIsArt7 小时前
C#环境中部署MQTT客户端
开发语言·c#
CSDN_RTKLIB8 小时前
模型空间、布局控件、自定义块
c#
z落落8 小时前
C# WinForm TCP 服务器+WinForm TCP 客户端
服务器·tcp/ip·c#
csdn_aspnet9 小时前
C# 多个串口多个线程发送数据和接收数据
c#·串口·thread·com·serialport
玹外之音9 小时前
Codex CLI 非交互模式:把 AI 接入你的 CI/CD 流水线
人工智能·ci/cd·交互
智恒百亿17 小时前
RTX 5090 全场景技术应用解析:从游戏算力到专业生产力落地
大数据·服务器·游戏
cd_9492172118 小时前
AI纹理和Substance Painter手绘纹理哪个更适合游戏资产制作?
人工智能·游戏·substance painter
德迅云安全-上官18 小时前
游戏攻防反套路:德迅云安全游戏盾如何破解黑产的“低成本精准打击”
网络·安全·游戏
sramdram20 小时前
语音识别芯片类别有哪些?离线语音识别芯片交互方案分析
人工智能·交互·语音识别·语音识别芯片·离线语音识别芯片
德迅云安全杨德俊21 小时前
游戏攻防反套路:游戏盾如何破解黑产的“低成本精准打击”
网络·安全·游戏