【问题标题】:unity : put clones on array and add back button that destory the last clone till the firstunity :将克隆放在数组上并添加后退按钮,将最后一个克隆销毁到第一个
【发布时间】:2021-11-24 22:10:53
【问题描述】:

我对统一非常陌生,我正在尝试做我的第一场比赛。我想将克隆对象放在数组上,然后添加一个后退按钮来破坏最后一个克隆,我试图制作数组,但它只让我克隆 1 个对象,然后我什么也做不了,谢谢你的帮助。 我有这个代码:

public class TouchSpwan : MonoBehaviour

public GameObject prefab;
public GameObject clone;
public Rigidbody rot;
public Camera mainCamera;
public FixedTouchField touchField;
public float gridsize;

void Update()
{
        if (Input.GetMouseButtonDown(0))
         {
                
             Vector3 touchPos = mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 9.8f));
             touchPos.x = Mathf.Floor(touchPos.x / gridsize);
             touchPos.z = Mathf.Floor(touchPos.z / gridsize);
             Vector3 result = new Vector3((float)touchPos.x * gridsize,touchPos.y, (float)touchPos.z * gridsize);
             if (touchField.Pressed == true)
             {
                    clone = Instantiate(prefab, result, prefab.transform.rotation);
                    clone.transform.parent = gameObject.transform;
            }
    }
}

【问题讨论】:

    标签: arrays unity3d clone


    【解决方案1】:

    首先,你的 GameObject 克隆,不必是公共类成员。而不是

    clone = Instantiate(prefab, result, prefab.transform.rotation);
    clone.transform.parent = gameObject.transform;
    

    你可以说:

     GameObject clone = Instantiate(prefab, result, prefab.transform.rotation);
     clone.transform.parent = gameObject.transform;
    

    并去掉顶部的声明:

    public GameObject clone;
    

    检查鼠标左键是否被按下后,你会额外检查一些 touchField.Pressed,不确定为什么,但如果你删除它,你可以在鼠标指针所在的地方生成尽可能多的克隆对象随你喜欢。

    在将这些对象存储在数组中时,您只需声明一个 GameObjects 数组并在实例化后添加每个克隆。您确实需要为克隆设置某种 maxLimit。

    1. 声明arr:private GameObject[] clonesArray;
    2. 初始化它:clonesArray = new GameObject[maxNumberOfClones];

    完成后,您可以在实例化后将每个克隆添加到数组中:

    GameObject clone = Instantiate(prefab, result, prefab.transform.rotation);
    clone.transform.parent = gameObject.transform;
    clonesArray[currentIndex] = clone;
    currentIndex++;
    

    您需要跟踪 currentIndex,从 0 开始,然后在将克隆添加到数组后将其递增。然后要销毁克隆,您需要从数组中访问它并使用 Destroy()。不要忘记减少索引计数器。

    Destroy(clonesArray[currentIndex]);
    currentIndex--;
    

    希望对你有帮助:D

    【讨论】:

    • 现在试试这个非常感谢,touch field.pressed 存在,所以如果我触摸中间的面板,它只能克隆对象,因为我只需要在中间。
    • 然后小心touchField.pressed。确保将其适当地设置为 true/false。在处理布尔值时,一个非常常见的错误是有人将其设置为 true,然后又忘记将其设置为 false。
    • 工作疯狂的好人,非常感谢!祝你有美好的一天!
    • 没问题的人,很高兴我能帮上忙 :)
    猜你喜欢
    • 2016-02-19
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 2022-01-20
    • 1970-01-01
    • 2016-03-15
    相关资源
    最近更新 更多