【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); 
    }
}
相关推荐
z落落21 分钟前
C# 四种特殊类:抽象类、密封类、静态类、部分类
开发语言·c#
x138702859571 小时前
c语言排雷游戏(基础版9*9)
c语言·算法·游戏
nnsix1 小时前
Unity 贴图压缩格式 笔记
笔记·unity·贴图
王cb2 小时前
WinRT Server and Client c#
开发语言·c#
咸鱼翻身小阿橙2 小时前
在VScode使用C#并且调用opencv库
vscode·opencv·c#
wgc2k4 小时前
Oops Framework-5-GUI资源的图集打包方式
游戏·cocos2d
海兰4 小时前
【红楼梦:第二篇】梦境漫游,详细设计指南
人工智能·游戏
xiaoshuaishuai85 小时前
C# 多线程之间对比
java·开发语言·c#
开开心心_Every7 小时前
解决打印机共享难题的实用工具
linux·b树·安全·游戏·随机森林·pdf·计算机外设
এ慕ོ冬℘゜9 小时前
【双月日期范围选择器】博客(可直接交作业 / 上线)
前端·javascript·交互·jquery