【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); 
    }
}
相关推荐
夏霞2 小时前
c# signlar 客户端传递参数给服务端配置方法
开发语言·c#
武藤一雄2 小时前
从零构建C# OOP 知识体系
windows·microsoft·c#·.net·.netcore·oop
唐青枫3 小时前
C#.NET ConcurrentStack<T> 深入解析:无锁栈原理、LIFO 语义与使用边界
c#·.net
CDN3604 小时前
360CDN 全系列产品体验:CDN / 高防 / SDK 游戏盾横向测评
运维·安全·游戏
小贺儿开发4 小时前
【Arduino与Unity交互探究】03 超声波测距模块
unity·arduino·串口通信·传感器·videoplayer·硬件交互
aini_lovee5 小时前
C# 实现邮件发送源码(支持附件)
开发语言·javascript·c#
CDN3606 小时前
中小团队加速 + 防护方案:360CDN+SDK 游戏盾实测
运维·游戏·网络安全
cxr8287 小时前
OpenClaw与NetLogo之间的调用与数据交互机制
人工智能·交互·netlogo·openclaw
WarrenMondeville9 小时前
1.Unity面向对象-单一职责原则
unity·设计模式·c#
WarrenMondeville9 小时前
2.Unity面向对象- 开闭原则
unity·游戏引擎·开闭原则