【问题标题】:How to instantiate next prefab in array on click on button?如何在单击按钮时实例化数组中的下一个预制件?
【发布时间】:2019-08-02 13:29:21
【问题描述】:

我想在数组中实例化新的预制件,并在用户单击下一个按钮或上一个按钮时删除旧的预制件。

我有类似这样的游戏对象预制数组:

public GameObject[] prefabMoles = new GameObject[3];
 GameObject[] moles = new GameObject[3];
 
 void Start () {
 
     for(int i = 0; i < prefabMoles.Length; i++)
     {
         moles[i] = (GameObject) GameObject.Instantiate(prefabMoles[i], new Vector3((i-1)*5, 0, 0), Quaternion.identity);
     }
 
 }

所以现在我想在画布上添加按钮,该按钮将是下一个字符,前一个将返回数组中的一个数字。

例如: 我有 Moles 数组,我实例化了 moles[2]; 单击下一个按钮时,我想销毁 moles[2] 并实例化 moles[3]。

当我们在 moles[3] 上并且当我们单击上一个时,我们必须销毁 moles[3] 并实例化 moles[2]。

产生一些新的效果会很棒,但没关系。 然后在实例化新的按钮时必须弹出解锁或选择角色是否解锁。

如果可能的话,非常感谢社区提供的帮助。

【问题讨论】:

    标签: c# unity3d game-development


    【解决方案1】:

    如果您想做的是让您的按钮创建一个新按钮并销毁旧按钮,您可以执行这个可以添加到按钮操作的功能。

    它看起来像:

    int currentIndex = 0;
    GameObject currentObject;
    
    void Start()
    {
         //Instantiate initial object
        currentObject = Instantiate(Moles[currentIndex]);
    }
    
    public void Previous()
    {
        Destroy(currentObject);
        currentIndex --;
        currentIndex = currentIndex < 0 ? Moles.Length : currentIndex;
        currentObject = Instantiate(Moles[currentIndex]);
        SpawnEffects();
    }    
    
    public void Next()
    {
        Destroy(currentObject);
        currentIndex ++;
        currentIndex = currentIndex > Moles.Length ? 0 : currentIndex;
        currentObject = Instantiate(Moles[currentIndex]);
        SpawnEffects();
    }
    
    void SpawnEffects()
    {
        //put your desired Effects
    }
    

    基本上,您正在跟踪已创建的内容以及您想要制作的下一个项目。

    【讨论】:

      猜你喜欢
      • 2018-07-29
      • 1970-01-01
      • 2014-11-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多