【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); 
    }
}
相关推荐
L X..20 小时前
Unity反射调用 ReactiveProperty<T>(泛型类型)内部方法时崩溃
unity·c#·游戏引擎·.net
缺点内向1 天前
C# 中 Excel 工作表打印前页面边距的设置方法
c#·.net·excel
游坦之1 天前
基于Java Swing的智能数据结构可视化系统 | 支持自然语言交互的AI算法助手
java·数据结构·交互
向宇it1 天前
【推荐100个unity插件】将您的场景渲染为美丽的冬季风景——Global Snow 2
unity·游戏引擎·风景
浅丿忆十一1 天前
关于unity一个场景中存在多个相机时Game视图的画面问题
unity·游戏引擎
wuqingshun3141591 天前
蓝桥杯 填字母游戏
游戏·职场和发展·蓝桥杯
雪芽蓝域zzs1 天前
uniapp AES 加密解密
开发语言·uni-app·c#
迎風吹頭髮1 天前
Linux内核架构浅谈2- Linux内核与硬件交互的底层逻辑:硬件抽象层的作用
linux·架构·交互
WLJT1231231231 天前
方寸之间见天地:新兴高端印章的当代破局与价值重构
unity·游戏引擎
weixin_456904271 天前
C# 中的回调函数
java·前端·c#