【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); 
    }
}
相关推荐
玉梅小洋5 分钟前
Unity Muse 完整使用文档:Sprite+Texture专项
unity·ai·游戏引擎
晚霞的不甘9 分钟前
Flutter for OpenHarmony 进阶实战:打造 60FPS 流畅的物理切水果游戏
javascript·flutter·游戏·云原生·正则表达式
开开心心_Every18 分钟前
A3试卷分割工具:免费转为A4格式可离线
游戏·随机森林·微信·pdf·excel·语音识别·最小二乘法
yngsqq1 小时前
批量裁剪——CAD一键根据裁剪框裁剪
c#
能源革命2 小时前
Three.js、Unity、Cesium对比分析
开发语言·javascript·unity
j_xxx404_2 小时前
C语言:进阶版贪吃蛇游戏(含有穿墙模式)附源码
游戏
BlackWolfSky4 小时前
鸿蒙中级课程笔记3—ArkUI进阶3—给应用添加交互(手势)
笔记·华为·交互·harmonyos
鸣弦artha4 小时前
Flutter框架跨平台鸿蒙开发——ListView交互与手势详解
flutter·交互·harmonyos
开开心心_Every4 小时前
手机PDF处理工具:支持格式转换与批注
游戏·微信·智能手机·pdf·逻辑回归·excel·语音识别
njsgcs4 小时前
ppo 游戏导航视觉 基于cnn 两个动作空间 训练120轮记录
游戏·ppo