在过去的几周中,我一直在尝试Unity。我还很新。我稍微介绍了ECS,计算着色器等,但是由于复杂性,如果不需要,我真的不想实现这些解决方案。默认的Unity物理引擎真的不能立即处理带有RigidBodies的500个多维数据集实例吗?还是我做事的方式对性能特别不利?这是我正在使用的代码;它只是一个空GameObject上的一个脚本。实例化500个多维数据集时,它的速度降低到16FPS,然后通过“刚体MoveTowards”一次移动它们时,它的速度降低到0.3 FPS。using System.Collections;using System.Collections.Generic;using UnityEngine;public class SpawnAndMove : MonoBehaviour{ public TargetCube TargetCube; public GameObject CubePrefab; public Vector3 brickPosition = new Vector3(10, 0, 0); GameObject[] objects; int moveCubeInstances; // Start is called before the first frame update void Start() { StartCoroutine(Countdown()); } IEnumerator Countdown() { yield return new WaitForSeconds(3f); for (int i = 0; i < 500; i++) { var cubeClone = Instantiate(CubePrefab, transform.position + brickPosition, transform.rotation); cubeClone.tag = "CubeInstance"; } objects = GameObject.FindGameObjectsWithTag("CubeInstance"); yield return new WaitForSeconds(3f); moveCubeInstances = 1; while (moveCubeInstances == 1) { for (int i = 0; i < 500; i++) { objects[i].GetComponent<Rigidbody>().transform.position = Vector3.MoveTowards(objects[i].GetComponent<Rigidbody>().transform.position, TargetCube.transform.position, 12f); } yield return new WaitForFixedUpdate(); } print("exited while loop"); }}多谢您的协助。 最佳答案 您对FindGameObjectsWithTag的调用不仅会搜索新的500个对象,还会搜索此场景中的所有其他对象,从而进行了额外的搜索transform已被缓存的字段,调用它无需执行GetComponent<>Instantiate是一个非常困难的操作,最好事先进行操作,您甚至可以将其分成几帧,例如每帧50次,但绝对不是一帧500次,而是使用Pooling()using System.Collections;using System.Collections.Generic;using UnityEngine;public class SpawnAndMove : MonoBehaviour{ public TargetCube TargetCube; public Rigidbody CubePrefab; public Vector3 brickPosition = new Vector3(10, 0, 0); Rigidbody[] objects; int moveCubeInstances; void Start() { StartCoroutine(Countdown()); } IEnumerator Countdown() { yield return new WaitForSeconds(3f); objects = new Rigidbody[500]; for (int i = 0 ; i < 500 ; i++) { Rigidbody cubeClone = Instantiate(CubePrefab, transform.position + brickPosition, transform.rotation); cubeClone.tag = "CubeInstance"; objects[i] = cubeClone; if (i % 50 == 0) { yield return new WaitForFixedUpdate(); } } yield return new WaitForSeconds(3f); moveCubeInstances = 1; while (moveCubeInstances == 1) { for (int i = 0 ; i < 500 ; i++) { objects[i].transform.position = Vector3.MoveTowards(objects[i].transform.position, TargetCube.transform.position, 12f); } yield return new WaitForFixedUpdate(); } print("exited while loop"); }}
10-01 01:33
查看更多