【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); 
    }
}
相关推荐
Rabbit_QL2 小时前
【CI/CD】01_为什么手动部署是个危险游戏
游戏·ci/cd
weixin_408099675 小时前
图片去水印 API 接口实战:网站如何实现自动去水印(Python / PHP / C#)
图像处理·人工智能·python·c#·php·api·图片去水印
:mnong8 小时前
Superpowers 项目设计分析
java·c语言·c++·python·c#·php·skills
我是唐青枫8 小时前
C#.NET 分布式事务 深入解析:TCC、Saga、Outbox 与落地取舍
分布式·c#·.net
上海云盾安全满满9 小时前
如何彻底解决游戏被攻击问题
游戏
dddddppppp1239 小时前
mfc实现的贪吃蛇游戏
c++·游戏·mfc
CSharp精选营9 小时前
.NET 8 性能优化实战:让你的应用起飞
性能优化·c#·.net·技术干货
mxwin9 小时前
Unity Shader 渲染队列 (Render Queue):控制 Geometry、Transparent、Overlay 等队列确保半透明物体渲染正确
unity·游戏引擎
CDN3609 小时前
SDK 游戏盾接入闪退 / 初始化失败?依赖冲突与兼容修复
运维·游戏·网络安全
mxwin10 小时前
Unity Shader Alpha Test 与 Alpha Blend:透明度测试与混合的实现及排序问题
unity·游戏引擎