【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); 
    }
}
相关推荐
darkhorsefly5 小时前
玩24算的益处
学习·游戏·24算
huwuhang6 小时前
DOS模拟器 DOSBox-X模拟器使用教程和DOS游戏合集3000+分享
游戏·电脑·游戏程序·游戏机·安卓软件
木斯佳9 小时前
HarmonyOS 6实战:HarmonyOS轻量化交互的两种方案改造与实践(上)
交互·harmonyos
芙莉莲教你写代码11 小时前
Flutter 框架跨平台鸿蒙开发 - 气泡消除游戏
flutter·游戏·华为·harmonyos
山檐雾13 小时前
OctreeNode
unity·c#·八叉树
GEO研究生14 小时前
深圳高端游戏主板选哪个品牌?华硕、七彩虹、技嘉、微星产品线解析与选购指南
游戏
WarPigs15 小时前
Unity协程返回值的解决方案
unity·游戏引擎
木斯佳15 小时前
HarmonyOS 6实战:HarmonyOS轻量化交互的两种方案改造与实践(下)
华为·交互·harmonyos
QfC92C02p16 小时前
C# 中的 Span 和内存:.NET 中的高性能内存处理
java·c#·.net
LcGero17 小时前
Lua + Cocos Creator 实战:用 Lua 驱动 UI 与游戏逻辑
游戏·ui·lua