【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); 
    }
}
相关推荐
WarPigs2 小时前
Unity渲染问题记录
unity·游戏引擎
bugcome_com2 小时前
C# 运算符详解:类型、实例及优先级
c#
不绝1912 小时前
导入3D模型时相关参数设置/Model标签页/Rig标签页/Avatar相关参数/Animation标签页/Materia标签页
unity·游戏程序
好家伙VCC2 小时前
# 发散创新:基于ARCore的实时3D物体识别与交互开发实战 在增强现实(
java·python·3d·ar·交互
无巧不成书02183 小时前
【RN鸿蒙教学|第8课时】表单优化+AsyncStorage数据持久化(本地缓存)+ 多终端兼容进阶
react native·缓存·华为·交互·harmonyos
~央千澈~3 小时前
抖音弹幕游戏开发之第9集:pyautogui进阶 - 模拟鼠标操作·优雅草云桧·卓伊凡
开发语言·python·游戏
C#程序员一枚3 小时前
Web Service 和 Web API
c#
悠哉悠哉愿意4 小时前
【强化学习学习笔记】马尔科夫决策过程
笔记·学习·交互·强化学习
陈天伟教授4 小时前
人工智能应用- 搜索引擎:02. 搜索引擎发展史
人工智能·深度学习·神经网络·游戏·搜索引擎·机器翻译