因此,我一直在设置此测试以实现flyweight模式。在这里,我创建一个对象类和一个工厂,以基本生成具有不同属性(在这种情况下为颜色,大小和形状)的相同类型的对象。因此,每个属性都有一个下拉菜单,还有一个用于创建对象的按钮。我想在工厂类中使用getobject函数创建对象,但似乎无法正确创建它。我得到了形状,但没有颜色或大小。它与我为该函数设置的参数有关。我不想做我现在正在做的事情来生成立方体和圆柱体。那只是一个测试。如果有人可以提出解决方案,我感谢您。
public class FlyWeight : MonoBehaviour
{
public Button CreateButton;
List<string> colors = new List<string>() { "Choose Color", "Red", "Blue", "Green" };
List<string> shapes = new List<string>() { "Choose Shape", "Sphere", "Cube", "Cylinder" };
List<string> sizes = new List<string>() { "Choose Size", "Small", "Medium", "Large" };
public Dropdown Shapes;
public Dropdown Colors;
public Dropdown Sizes;
private void Start()
{
Button button = CreateButton.GetComponent<Button>();
Shapes.AddOptions(shapes);
Colors.AddOptions(colors);
Sizes.AddOptions(sizes);
}
public void TaskOnClick()
{
if (Shapes.value == 1)
{
var sphere= Factory.getObject(GameObject.CreatePrimitive(PrimitiveType.Sphere), getSize(), getColor());
}
else if (Shapes.value == 2)
{
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.GetComponent<Renderer>().material.color = getColor();
cube.transform.localScale = getSize();
}
else if (Shapes.value == 3)
{
var cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
cylinder.GetComponent<Renderer>().material.color = getColor();
cylinder.transform.localScale = getSize();
}
}
public Color getColor()
{
if (Colors.value == 1) { return Color.red; }
else if (Colors.value == 2) { return Color.blue; }
else if (Colors.value == 3) { return Color.green; }
else return Color.white;
}
public Vector3 getSize()
{
if (Sizes.value == 1) { return gameObject.transform.localScale = new Vector3(1, 1, 1); }
else if (Sizes.value == 2) { return gameObject.transform.localScale = new Vector3(2, 2, 2); }
else { return gameObject.transform.localScale = new Vector3(3, 3, 3); }
}
}
对象类
public class Object
{
private Color color;
private Vector3 size;
private GameObject shape;
private int x, y;
public Object (GameObject shape, Vector3 size,Color color)
{
this.color = color;
this.size = size;
this.shape = shape;
}
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
}
工厂类
public class Factory
{
private static List<Object> objects = new List<Object>();
public static Object getObject(GameObject shape,Vector3 size, Color color)
{
Object obj = null;
if (obj == null)
{
obj = new Object(shape, size, color);
objects.Add(obj);
}
return obj;
}
}