RPG小游戏创建游戏中的交互
- 创建可交互的物体的公共的父类(Interactable)
- InteractableObject 类
- NPCObject 类
- PickableObject 类
创建可交互的物体的公共的父类(Interactable)
InteractableObject 类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class InteractableObject : MonoBehaviour
{
private NavMeshAgent playerAgent;
private bool haveInteeacted;
public void OnClick(NavMeshAgent playerAgent)
{
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 类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPCObject : InteractableObject
{
public new string name;
public string[] contentList;
protected override void Interact()
{
DialogueUI.Instance.Show(name, contentList);
}
}
PickableObject 类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickableObject : InteractableObject
{
public ItemScriptObject itemSO;
protected override void Interact()
{
Destroy(this.gameObject);
InventoryManager.Instance.AddItem(itemSO);
}
}