将多个预制件分配给一个只允许添加一个的脚本

2024-03-30

我有一个脚本,它使用 LeanTween 将对象(预制)放入预制路径上,效果很好。

其工作原理是,您可以将一个对象分配给附加有 Moveable 脚本的“路径添加器”(MoveController)。

但是,我需要能够将运行时创建的新预制件添加到 MoveController,以便它们遵循路径。

那么我将如何在运行时使实例化对象附加到 MoveController。

谢谢。

可移动脚本,还实例化预制件

public class Moveable : MonoBehaviour
{
    [SerializeField] private float _speedMetersPerSecond = 25f;

    private Vector3? _destination;
    private Vector3 _startPosition;
    private float _totalLerpDuration;
    private float _elapsedLerpDuration;
    private Action _onCompleteCallback;
    public GameObject Electron;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
        var NextOnPath = Instantiate(Electron, transform.position, Quaternion.identity);
            NextOnPath.AddComponent<Moveable>();
        }

        if (_destination.HasValue == false)
            return;

        if (_elapsedLerpDuration >= _totalLerpDuration && _totalLerpDuration > 0)
            return;

        _elapsedLerpDuration += Time.deltaTime;
        float percent = (_elapsedLerpDuration / _totalLerpDuration);
        Debug.Log($"{percent} = {_elapsedLerpDuration} / {_totalLerpDuration}");

        transform.position = Vector3.Lerp(_startPosition, _destination.Value, percent);
    }

    public void MoveTo(Vector3 destination, Action onComplete = null)
    {
        var distanceToNextWaypoint = Vector3.Distance(transform.position, destination);
        _totalLerpDuration = distanceToNextWaypoint / _speedMetersPerSecond;

        _startPosition = transform.position;
        _destination = destination;
        _elapsedLerpDuration = 0f;
        _onCompleteCallback = onComplete;
    }
}

移动控制器脚本

using System.Linq;

public class MoverController : MonoBehaviour
{
    [SerializeField] private Moveable target;
    private List<Transform> _waypoints;
    private int _nextWaypointIndex;


    private void OnEnable()
    {
        _waypoints = GetComponentsInChildren<Transform>().ToList();
        _waypoints.RemoveAt(0);
        MoveToNextWaypoint();
    }

  private void MoveToNextWaypoint()
    {
        var targetWaypointTransform = _waypoints[_nextWaypointIndex];
        target.MoveTo(targetWaypointTransform.position, MoveToNextWaypoint);
        target.transform.LookAt(_waypoints[_nextWaypointIndex].position);
        _nextWaypointIndex++;

if (_nextWaypointIndex >= _waypoints.Count)
            _nextWaypointIndex = 0;
        
    }
}

如果我需要澄清任何事情,请告诉我。

我知道这是一个相当沉重的问题,但我将非常感谢任何帮助!

Solution

Moveable:
public class Moveable : MonoBehaviour
{
    [SerializeField] private float _speedMetersPerSecond = 25f;
    public List<Moveable> moveables = new List<Moveable>();
    private Vector3? _destination;
    private Vector3 _startPosition;
    private float _totalLerpDuration;
    private float _elapsedLerpDuration;
    private Action _onCompleteCallback;
    public GameObject Electron;

   // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Moveable NextOnPath = Instantiate(Electron, transform.position, Quaternion.identity).GetComponent<Moveable>();
            moveables.Add(NextOnPath.GetComponent<Moveable>());
            MoverController.instance.targets.Add(NextOnPath.GetComponent<Moveable>());
        }
}
}

移动控制器:

public List<Moveable> targets;
    [SerializeField] private Moveable target;
    private List<Transform> _waypoints;
    private int _nextWaypointIndex;
    public static MoverController instance;
private void MoveToNextWaypoint()
    {
        for (int i = 0; i < targets.Count; i++)
        {
            var targetWaypointTransform = _waypoints[_nextWaypointIndex];
            targets[i].MoveTo(targetWaypointTransform.position, MoveToNextWaypoint);
            targets[i].transform.LookAt(_waypoints[_nextWaypointIndex].position);
            _nextWaypointIndex++;

            if (_nextWaypointIndex >= _waypoints.Count)
                _nextWaypointIndex = 0;
        }
    }

注意:解决方案中仅显示更改的部分


是的,如果您使用Array https://learn.microsoft.com/vi-vn/dotnet/csharp/programming-guide/arrays/然后您可以添加任意数量的预制件。您仍然需要在脚本中设置代码来处理多个预制件。

不过,听起来您可能不了解 C# 和 Unity 的基础知识,您可能想参加课程、阅读教程或观看 Youtube 视频。


Update

Because your question is so broad, I cannot just give you the code. That's something you should pay a coder for. But I will tell you the general ideas of what will need to be done.
  1. 在 Moveable 类中,您需要实例化后跟踪您的 var NextOnPath https://forum.unity.com/threads/save-instantiated-objects.709040/他们。执行此操作的一个好方法(只要您不打算将任何内容转换为 JSON)就是使用 List。 例如:

    List<Moveable> moveables = new List<Moveable>();
    
    void Update()
    {
        //Some code before - with instantiation
        //It is best to track items by the script that you will use since you can just use moveables[i].gameObject to access the gameObject and moveables[i].transform to access transform
        moveables.Add(NextOnPath.GetComponent<Moveable>());
        //Some code after
    }
    
  2. 您可以通过以下方式节省计算能力将 Moveable 脚本添加到您的 Electron 预制件中 https://forum.unity.com/threads/adding-a-script-to-a-prefab.19843/所以你使用:Moveable nextOnPath = Instantiate(electron, transform.position, Quaternion.identity).GetComponent<Moveable>();

  3. Look up 辛格尔顿 https://gamedevbeginner.com/singletons-in-unity-the-right-way/,您可以使用它轻松地为您的 MoverController 类赋值:

public static MoverController instance;
void Awake()
{
    if (instance == null)
    {
        instance = this;
    }
    else
    {
        Destroy(gameObject);
        return;
    }

    DontDestroyOnLoad(gameObject);
}

然后在 Moveable 类中只需将其添加到 MoverController

//Requires changing the above code

    void Update()
    {
        //Some code before - with instantiation
        MoverController.instance.targets.Add(NextOnPath.GetComponent<Moveable>());
        //Some code after
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将多个预制件分配给一个只允许添加一个的脚本 的相关文章

随机推荐

  • 为什么我不能在 Konva.Shape.fillPatternImage(imageObj) 中使用 Konva.Image()?

    以下是来自的示例Konvajs http konvajs github io docs shapes Image html加载图像的库 var imageObj new Image imageObj onload function var
  • Mongoose 模式要求数组可以为空

    我有这个架构 var StuffSchema new mongoose Schema id type String required true unique true name type String required true mongo
  • 构建 Java EE 6 项目时出现 FilerException

    我在 Netbeans 7 中有一个 Java EE 6 项目 当我在 IDE 中编译并启动它时 该项目运行良好 但是 当我清理和构建项目时 我得到了 java lang RuntimeException javax annotation
  • 如何提高@patch和MagicMock语句的可读性和可维护性(避免长名称和字符串标识)?

    在我的测试代码中 我有很多样板表达式 Magic return 我还有很长的字符串来标识要模拟的函数的路径 重构期间不会自动替换字符串 我更愿意直接使用导入的函数 示例代码 from mock import patch MagicMock
  • 如何在远程存储库上运行 hg recovery 命令

    在 teamcity 中运行构建时出现以下错误 Failed to collect changes error C Program Files TortoiseHg hg exe config ui interactive False pu
  • 在 cakephp 中分配布局

    我们可以在该特定控制器中为整个控制器定义一个布局吗 我之前已经在应用程序控制器的过滤器之前用于此目的 但它不再解决它 所以我需要在控制器中应该有一些适用于的布局定义该控制器的所有操作 Regards use it 在你的行动中 this g
  • JavaScript - 对象字面量的优点

    我读过 我应该使用对象文字 而不是简单地编写一堆函数 对象字面量有什么优点 有例子吗 正如 Russ Cam 所说 您可以避免污染全局命名空间 这在当今组合来自多个位置 TinyMCE 等 的脚本时非常重要 正如 Alex Sexton 所
  • 如何使用 WebApplicationFactory 覆盖 Autofac 容器中的服务

    我正在使用 WebApplicationFactory 编写一些集成测试 我使用 Autofac 作为我的依赖解析器 在我的测试中 我试图覆盖其中一项注册 以便我可以模拟其中一项依赖项 使用aspnetcore默认的ConfigureSer
  • 如何将html5画布保存到服务器

    我将一些图像加载到我的画布上 然后在加载后我想单击一个按钮将该画布图像保存到我的服务器上 我可以看到脚本工作正常 直到它到达 toDataURL 部分并且我的函数停止执行 我究竟做错了什么 这是我的代码
  • Android View 背景意外变化

    我正在构建一个具有大量屏幕的应用程序 大多数屏幕的顶部都有一个带有背景颜色的视图 我经常使用 view setBackgroundColor color 更改颜色 奇怪的事情来了 有时在设置一个视图的颜色后 例如 f14fb7 在应用程序中
  • 将阿拉伯数字转换为英语

    我正在寻找一种将阿拉伯数字字符串 转换为英语的方法 数字字符串 0123456789 Private Sub Button1 Click ByVal sender As System Object ByVal e As System Eve
  • 如何将多个局部变量传递给嵌套部分

    这应该是非常简单且有据可查的 我已经这样做了好几次了 尽管有些事情仍然让我很烦恼 我有一个调用嵌套部分的部分结构 在某个时刻一render调用需要将额外的变量传递给部分 尽管部分的渲染失败并显示 undefined local variab
  • Swing 菜单 Java 7 mac osx

    我一直在 mac os x 上测试我的 Swing 应用程序 它在小程序上运行 当我在浏览器中运行此小程序时 我注意到 JMenus JMenuItems 上的鼠标悬停无法正常工作 这是一个重现该问题的小程序 package com mac
  • 如何在 Sublime Text 中使用控制台

    我正在使用 Sublime Text 2 来编写程序 并希望在其中运行控制台来编译和运行它们 有没有办法在 Sublime Text 2 中嵌入控制台命令行 已经在那里了吗 我同时使用 Windows 和 Linux 我想你可以尝试创建一个
  • 推送事件不会触发推送路径上的工作流程

    我目前正在测试 GitHub Actions 工作流程这个存储库 https github com GuillaumeFalourd poc github actions 我正在尝试使用这个工作流程 https github com Gui
  • 禁止 (#403) - 你不能执行此操作 [Yii2]

    我尝试添加菜单map在后端 我用yii2 advanced 这是我的 控制器 代码 public function actionMap return this gt render map 但是 当我尝试使用此网址访问它时http local
  • opencv中如何根据深度颜色分割连通区域

    I have a picture like which i need to segment the picture into 8 blocks 我尝试过这种阈值方法 img gray cv2 imread input file cv2 IM
  • 如何获得欧米茄(n)

    我有公式 a n n a n 1 1 a 0 0 如果没有主定理 我怎样才能从中得到 Omega Theta 或 O 表示法 或者有人有一个很好的网站来理解解释 马斯特定理甚至不适用 所以不能使用它并不是太大的限制 此处有效的方法是猜测上限
  • 在 R 中:计算精确率/召回率曲线下的面积 (AUPR)?

    假设我有两个矩阵 A代表标签矩阵 B代表A对应的预测概率矩阵 现在我想根据矩阵A和B计算AUPR 精确率 召回率曲线下的面积 对于常见的AUC Area Under Precision Recall Curve ROC Curve R中有很
  • 将多个预制件分配给一个只允许添加一个的脚本

    我有一个脚本 它使用 LeanTween 将对象 预制 放入预制路径上 效果很好 其工作原理是 您可以将一个对象分配给附加有 Moveable 脚本的 路径添加器 MoveController 但是 我需要能够将运行时创建的新预制件添加到