Unity2D:禁用订单中的实例化预制件

时间:2018-08-01 19:31:44

标签: c# unity3d instantiation

我创建了一个脚本,该脚本可实例化各种不同的预制件(也可以实例化同一预制件中的多个预制件),这些脚本成为我称为插槽的父代(游戏对象)的子代。生成每个预制件后,便会在某个区域设置一个固定的变换位置,因此,如果我要让脚本在场景中的同一预制件(例如prefab1)的3个中生成,则所有三个prefab1都将具有相同的变换位置( (彼此叠放),并且也是该广告位的孩子。但是说,如果我在prefab2的4个中生成,则prefab2与prefab1会有不同的开始位置,但是被设置为与prefab1相同的父对象...希望我有道理!我想做的事: 有没有一种方法可以对所有实例化的预制件设置为active false,但是保留所生成的所有不同预制件之一,例如:

enter image description here

我要在图像上方绘制的黑匣子中将所有prefab1和prefab2设置为false,如果将prefab1 / prefab2设置为true,则我希望下一个将prefab1 / prefab2设置为true等。同样,我希望我有道理...这是我在预制件中生成的代码:

 void Update () {
   for (int x = 0; x < slotController; x++) {
            var item = Instantiate (ItemPrefab) as GameObject;
            itemPrefab.transform.position = transform.position;
            itemPrefab.transform.SetParent (slot.transform);
            itemPrefab.SetActive (true);
            if (slot.childCount < 0) {
                slotHolder.SetActive (false);
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用集合和LINQ来执行类似的操作。这是一个例子。 “物”类将是您的预制件。

对于每种类型的预制件,您基本上都有一个List集合,还有一个字典,用于存储所有这些列表,并具有用于访问它们的密钥。

(顺便说一下,Update方法意味着您的代码将在每一帧出现,因此可能不是一个好地方)

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        Dictionary<int, List<Thing>> prefabs = new Dictionary<int, List<Thing>>();

        // add a few items to the lists
        prefabs.Add(1, new List<Thing>(){ new Thing("Thing1"), new Thing("Thing1") });
        prefabs.Add(2, new List<Thing>(){ new Thing("Thing2"), new Thing("Thing2"), new Thing("Thing2") });

        var keys = prefabs.Keys;
        // set everything inactive except the first one
        foreach(int i in keys){
            prefabs[i].Skip(1).ToList().ForEach(x => x.active = false);
        }

        // print out the active state
        foreach(int i in keys){
            foreach(Thing t in prefabs[i]){
                Console.WriteLine("prefab " + i + "  active = " + t.active);
            }
        }
    }

    class Thing {
        public bool active = true;
        public String name = "";

        public Thing(String name){
        this.name = name;
        }
    }
}

结果:

prefab 1  active = True
prefab 1  active = False
prefab 2  active = True
prefab 2  active = False
prefab 2  active = False