工厂模式。
工厂模式不关心生产过程,只是将任务直接转换为产品的过程。
过程如下:
/*
* 工厂模式,不需要继承Mono(占用空间),动态加载游戏物体。
*
*/
public class TestFactory1
{
Sprite[] sprites;
//父物体
Transform parents;
/// 加载资源,准备生产的原料。
public void Initial()
{
//加载该文件下的所有spirite 有问题
sprites = Resources.LoadAll<Sprite>("Factory");
Debug.Log(sprites.Length);
//动态加载的游戏对象需要设置父物体
parents = GameObject.FindGameObjectWithTag("MainCavas").transform;
}
//动态创建游戏物体,将原料转换为产品,传入的参数游戏物体的索引以及游戏物体出现的位置(三元数组)
public GameObject CreateImage(int index, Vector3 pos)
{
//在内存中创建gameObject
GameObject gameObject = new GameObject();
gameObject.transform.SetParent(parents);
//动态设置位置
gameObject.transform.localPosition = pos;
//动态加载Image
Image image = gameObject.AddComponent<Image>();
//给Image赋值
//限制index的取值范围
index = index % sprites.Length;
image.sprite = sprites[index];
return gameObject;
}
}
工厂的调用:
在这里插入代码片`public class UseFactory : MonoBehaviour
{
TestFactory1 testFactory;
// Start is called before the first frame update
void Start()
{
testFactory = new TestFactory1();
testFactory.Initial();
}
int temcount=10;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//Debug.Log("一点击");
temcount++;
testFactory.CreateImage(temcount,Vector3.one*temcount*50);
}
}
}`