Hi,
I’m using Unity 2020.3.30f
This is really weird to me, I hope someone can share some insight on this.
In my game I use a script to create 8 “ghosts” which are used to wrap objects when they go offscreen.
Everything was working fine before I made a small change to the code to make things more performant. And somehow I made it almost 100x worse, by setting a grandparent before spawning the child.
The hiearchy:
- Ghosts
- Ghost 1
- prefab instance
- Ghost 2
- prefab instance
- etc…
This is the code, I commented in CAPS the part te causes the issue:
protected virtual void CreateGhosts()
{
Debug.Log("Create Ghosts "+gameObject);
m_GhostParent = new GameObject($"Ghosts - {name}").transform;
m_GhostParent.localPosition = Vector3.zero;
m_GhostParent.localRotation = Quaternion.identity;
for(int i = 0; i < 8; i++) {
var originalGhostChild = m_GhostPrefab == null ? gameObject : m_GhostPrefab;
GameObject ghostNesterInstance = Instantiate(m_GhostParent.gameObject, Vector3.zero, Quaternion.identity);
ghostNesterInstance.name = $"{originalGhostChild.name} Ghost {i}";
ghostNesterInstance.layer = originalGhostChild.layer;
ghostNesterInstance.tag = originalGhostChild.tag;
m_GhostTransforms[i] = ghostNesterInstance.transform;
// THIS LINE RIGHT HERE causes the instantiate below to take 800ms instead of 16ms
//m_GhostTransforms[i].SetParent(m_GhostParent);
var ghostElement = ghostNesterInstance.AddComponent<ScreenWrapBehaviorGhostElement>();
ghostElement.SetUp(this);
m_Ghosts[i] = ghostElement;
// Now create the instance of the child to set under the ghost element.
Transform ghostChildInstance = Instantiate(originalGhostChild, m_GhostTransforms[i]).transform;
ghostChildInstance.position = Vector3.zero;
if ((m_CircleCollider != null || m_BoxCollider != null)
&& m_Rigidbody != null && m_DamageOnTouch != null) {
SetupGhostCollider(ghostNesterInstance);
}
SetupGhostChild(i, ghostChildInstance);
}
// Set all ghost under parent: I DO THIS AT THE END BECAUSE IT DOESN'T CAUSE ISSUES
for(int i = 0; i < m_GhostTransforms.Length; i++) {
m_GhostTransforms[i].SetParent(m_GhostParent);
}
PositionGhost();
}
I’m just very curious why it happens.
In any case 16ms is way too long for spawning ghosts anyways, so I plan to refactor my code to only have a single ghost that teleports in the closest edge. And I’ll design my levels to avoid warping in corners.
That should make everything more performant.
(if there are other tips to make it more performants, ideas are welcomed. I need to make it as performant as possible since all objects: characters, projectiles, etc… can wrap)