c# - 如何在 Unity 上使用 C# 编写 Arrived Function
问题描述
当角色到达目的地时,我想得到回调。
但是我不想写入更新函数。如果我要写入 Update,我想编写巧妙而优雅的代码。
当我们制作游戏时,如果有设计模式。
让我教一下。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Unit : MonoBehaviour
{
[SerializeField] Vector3 targetPosition;
private NavMeshAgent agent;
private bool arrived;
private Transform myPosition;
void Start()
{
myPosition = GetComponent<Transform>();
agent = GetComponent<NavMeshAgent>();
agent.updateRotation = false;
agent.updateUpAxis = false;
}
void Update()
{
agent.SetDestination(targetPosition);
}
public void MoveTo(Vector3 position, float stopDistance, Action onArrivedAtPosition)
{
targetPosition = position;
// here!
if (arrived)
{
onArrivedAtPosition();
}
}
private void IsArrived()
{
if (Vector3.Distance(myPosition.position, agent.destination) < 1.0f)
{
arrived = true;
}
arrived = false;
}
}
解决方案
您可以创建一个像下面这样的脚本并将其附加到一个空的游戏对象,然后将该空的游戏对象放置在目标位置。确保您的 IsArrived 方法(在 Unit 脚本中)是公开的,并在空的 gameobjec 的 TargetPoint 脚本中分配单位。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetPoint : MonoBehaviour
{
public float radius = 1f;
public Unit unit = null;
private bool called = false;
private void Start()
{
SphereCollider c = gameObject.AddComponent<SphereCollider>();
c.radius = radius;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.green;
Gizmos.DrawSphere(transform.position, radius);
}
private void OnTriggerEnter(Collider other)
{
if (called)
{
return;
}
if(other.transform == unit.transform)
{
unit.IsArrived();
called = true;
}
}
}
推荐阅读
- python - 在 Python 中按索引提取 JSON 数据
- apache-poi - Quarkus Graalvm Apache POI - 对“Java_sun_font”的错误未定义引用
- scala - 替换嵌套映射中的值
- python - python - 如何从递归函数返回一个列表以获取python中数字的阶乘?
- javascript - 打字稿:使用“作为 HTMLElement”类型时出现意外标记
- javascript - Vue:使用 v-tab 为不同的选项卡显示不同的信息
- reactjs - React - 将状态传递给另一个组件 - 通过 URL 访问的组件
- javascript - 我想把这段代码变成一个可以从 html 表单调用的 keydown 函数
- python - 我怎样才能有 2 个输入 if 语句?
- google-cloud-platform - GCP:GBQ 每日查询显示在查询历史记录中,但未显示在预定查询中