【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); 
    }
}
相关推荐
kyh10033811203 分钟前
Cocos Creator 《打螺丝消除游戏》源码+实现
游戏·微信小程序·小程序·打螺丝小游戏源码·微笑小游戏源码
z落落15 分钟前
C# ToCharArray + foreach遍历 + String与StringBuilder
开发语言·c#
xiaoshuaishuai81 小时前
C# AvaloniaUI动态显示图片
开发语言·c#
元气少女小圆丶1 小时前
SenseGlove Nova 2+Unity开发笔记1
笔记·学习·unity
mxwin2 小时前
Unity URP下新技术MSSPT 取代SSR和光线追踪
unity·游戏引擎·shader
csdn_aspnet4 小时前
EasyModbus 与 C# 集成
c#·modbus·easymodbus
LF男男5 小时前
IBuilder.cs 接口
unity
JaydenAI6 小时前
[MAF预定义ChatClient中间件-06]利用ImageGeneratingChatClient开发专业图片生成Agent
ai·c#·agent·agent管道·chatclient中间件·chatclient管道
心之所向,自强不息6 小时前
# Unity MCP + Codex CLI 完整教程(Windows)
windows·unity·游戏引擎
csdn_aspnet8 小时前
Modbus TCP C# 客户端程序
服务器·网络·tcp/ip·c#