【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); 
    }
}
相关推荐
圣捷游戏13 小时前
教育游戏开发需要准备什么?一文讲清从0到1的完整准备清单(圣捷游戏15年经验分享)
游戏·游戏开发
学长毕设1 天前
基于SpringBoot的游戏攻略社区交流系统-附源码
spring boot·后端·游戏
一只大鸽子1 天前
游戏开发笔记7-Godot RPG游戏基础-场景切换、全局脚本
笔记·游戏·godot
赤生云电竞1 天前
云游戏边缘节点部署实践:机房选址与网络拓扑选型
网络·游戏·php
芝麻粒儿2 天前
Scratch少儿编程案例-鼠标控制练习
游戏·青少年编程·计算机外设·scratch·少儿编程
科技小登2 天前
DDoS防护选型测评:高防CDN、高防IP与SDK游戏盾怎么做同口径POC?
tcp/ip·游戏·ddos
zdr尽职尽责2 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
hcgeng2 天前
原生与 H5 如何交互
交互·h5
xx z3 天前
打开游戏提示 d3dx9_43.dll 缺失怎么办(DirectX 修复步骤)
windows·游戏·工具·软件
珍猪吃饲料3 天前
消息丢了、重复消费了,MQ 这套账该怎么算
游戏