目前正在为学校开发游戏。我们打算通过使用碰撞触发器在我们的角色登陆平台时实例化平台。我已成功触发它们,登陆它们然后触发实例化新平台。我现在的问题是,在9次触发后,游戏滞后,我觉得这种方法使用了太多的内存,这就是为什么在一段时间后游戏会滞后。
有更好的方法吗?
编辑:
public Transform[] spawnLocations;
public GameObject[] platform1;
public GameObject[] platformclone;
public float movespeed;
public bool moveRight;
void OnTriggerEnter2D (Collider2D col)
{
platformclone[0] = Instantiate(platform1[0], spawnLocations[0].transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
platformclone[1] = Instantiate(platform1[1], spawnLocations[1].transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
}
此脚本已附加到平台。然后,我们在初始平台下创建了两个空子对象,并对它们进行了预定位。当我们的角色落在平台上时,通过碰撞触发器,在下面创建两个平台(在层次结构中,这被标记为平台(克隆)。
Box Collider2D附加到角色,触发器被勾选。盒子collider2D在平台上。
当角色落在其中一个新平台上时,会创建两个新平台,然后标签变为平台(克隆)(克隆)。
整个事情一直重复,直到第9-10天左右角色仍然存在并且因为它们是一个盒子对撞机但没有看到平台,此时的游戏变得迟钝。
答案 0 :(得分:0)
我认为你想开发无限运行游戏。如果确实如此,则需要实例化可见的+ 1 perefab对象,并在传递预制件时将其转换为最后一个元素位置。你需要改变,而不是破坏和重建你的平台(我认为这是预制)。
修改强>
我不检查语法错误,下面的代码用于解释逻辑。
public Transform[] spawnLocations;
public GameObject[] platform1;
public GameObject[] platformclone;
public float movespeed;
public bool moveRight;
public List<GameObject> instantiatedPlatforms;
public int poolSize = 10;
void Start(){
//Pool Platforms
instantiatedPlatforms = new List<GameObject>();
instantiatedPlatforms.Add(Instantiate(platform1[0], Vector3.zero, Quaternion.Euler(0, 0, 0)) as GameObject); //you can set whatever position you want this is for initialization.
instantiatedPlatforms.Add(Instantiate(platform1[1], Vector3.zero, Quaternion.Euler(0, 0, 0)) as GameObject);
//If you have many platform1 objects. you can do it with loop
//for(int i=0;i<poolSize;i++){
// instantiatedPlatforms.Add(Instantiate(platform1[i], Vector3.zero, Quaternion.Euler(0, 0, 0)) as GameObject);
//}
//after that you can set first platform prefab
instantiatedPlatforms[0].transform.position = spawnLocations[0].transform.position;
instantiatedPlatforms[1].transform.position = spawnLocations[1].transform.position;
}
void OnTriggerEnter2D (Collider2D col)
{
//platformclone[0] = Instantiate(platform1[0], spawnLocations[0].transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
//platformclone[1] = Instantiate(platform1[1], spawnLocations[1].transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
//Get usedPrefabs
GameObject obj1 = instantiatedPlatforms[0];
GameObject obj2 = instantiatedPlatforms[1];
//Change Value
obj1.transform.position = Vector3.zero;
obj2.transform.position = Vector3.zero;
//Change List Position (Remove First insert last)
instantiatedPlatforms.Remove(0); //remove first and second elements
instantiatedPlatforms.Remove(0); //after first remove second member becomes first so need 2 times remove.
instantiatedPlatforms.Add(obj1); //set last
instantiatedPlatforms.Add(obj2);
//set new prefabs to spawn positions
instantiatedPlatforms[0].transform.position = spawnLocations[0].transform.position;
instantiatedPlatforms[1].transform.position = spawnLocations[1].transform.position;
}