【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); 
    }
}
相关推荐
张人玉16 小时前
C#如何使用FreeSql连接数据库
数据库·c#·freesql
赤生云电竞17 小时前
云游戏边缘节点部署:机房选址与网络拓扑优化实践 —— 基于GPU虚拟化与多级QoS的端到端时延控制
游戏
吴可可1231 天前
C#打断多段线实现方法
c#
Kari111 天前
医药和制造行业的外文文档批量翻译,排版怎么保住?
开发语言·c#·制造
芝麻粒儿2 天前
Scratch少儿编程案例-赛车与载具(1)
游戏·青少年编程·scratch·少儿编程·编程猫
jasmine02442 天前
GitHub 开源背单词游戏:四六级考研词库,拼写正确就能攻击
游戏·github·工具类
Warson_L2 天前
.NET 8 速成笔记 1:用 VS Code 做 C# / .NET 开发
c#·.net
Warson_L2 天前
.NET 8 速成笔记 9:C# 项目常见场景(基础设施篇)
c#·.net
Warson_L2 天前
.NET 8 速成笔记 8:C# 项目常见业务场景与写法(数据与业务篇)
c#·.net
Warson_L2 天前
.NET 8 速成笔记 3:作业清单
c#·.net