首页 > 解决方案 > 如何在 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;
    }
}

标签: c#unity3d

解决方案


您可以创建一个像下面这样的脚本并将其附加到一个空的游戏对象,然后将该空的游戏对象放置在目标位置。确保您的 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;
        }
    }

}

推荐阅读