首页 > 解决方案 > 如何将对象的起始位置定位在预制件的起始位置上,并且与结束位置相同?

问题描述

我的预制件由 3 个部分组成。比赛开始,立方体,比赛结束:

我的比赛预制件

如果您在“匹配开始”或“匹配结束”上单击鼠标,我做了什么,它将实例化另一个预制克隆。现在我想做的是,新克隆的预制件将从开始或结束(开始和结束都是比赛中的红色顶部和底部)以不同的旋转连接。

例如:

应该如何的示例

可能是 Z 上的 -90 新比赛或 90 上的 Z 或 45 但与上一场比赛不同,因为您不会看到它,它会像另一场比赛一样。

然后单击新匹配结束位置时的相同逻辑创建新匹配等等。

现在我的脚本的问题是它在其他地方创建了一个新的匹配:

问题

这是我正在使用的脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    public GameObject matchPrefab;

    private Transform[] StartEndPos;

    // Start is called before the first frame update
    void Start()
    {
        var match = Instantiate(matchPrefab);

        StartEndPos = match.GetComponentsInChildren<Transform>();
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f);

        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(mousePos);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                if (hit.transform.tag == "Match Start" || hit.transform.tag == "Match End")
                {
                    for (int i = 0; i < StartEndPos.Length; i++)
                    {
                        if (StartEndPos[i].name == hit.transform.name)
                        {
                            var ClonedMatch = Instantiate(matchPrefab, StartEndPos[i].transform.position, Quaternion.identity);
                        }
                    }
                }
                else
                {
                    Debug.Log("Nothing there");
                }
            }
        }
    }
}

标签: c#unity3d

解决方案


我刚刚测试了您的代码,它似乎可以正常工作 - 基本上。逻辑可能不起作用,但实例化可以。但是,您可以发布 Match 预制件的变换值的图片吗?您的比赛预制件可能未清零。确保您的预制件是 Position (x,y,z) = (0f, 0f, 0f)。如果不是这种情况,您将获得超级奇怪的实例化。


推荐阅读