Question

While working in Unity 3D i have encountered a 8ms self time on a method that actually just ran a few other methods. (so say the entire method took 10ms, the self time was 8ms, only 2ms went into "other methods". So those 8ms, have to come from the method as shown in the profiler)

After commenting stuff out, i noticed that the problem could be traced back to a few lines of code. The following method, when run 2200 times. Has a self ms of 8.

private bool checkPiece (GameObject targetPiece,int side){
    if(targetPiece == null) return false;
    Transform targetTransform = targetPiece.transform;
    Vector3 origin = myTransform.position;
        Vector3 target = targetTransform.position;
    /*
    ...
    */
    return false;
}

i tried to test out each of those, just doing :

Transform targetTransform = targetPiece.transform;

Already makes for a 2ms self time. Which is just terrible if you want to run on a decent frame rate. Besides the obvious like running this method less often. How can improve this behavior?

I have never seen unity go this high on just setting transforms and positions.

I have already tried to put the variables outside the method, so they would just get overwritten each update. This however makes no difference at all. (i suppose this is already optimized when building the code?)

Any help would be greatly appreciated.

Was it helpful?

Solution

When grabbing the transform of an object, or most components for that matter, you pay a price in computation. See if you can use caching to store your gameObject's transform before passing them into the function.

You can change this line

private bool checkPiece (GameObject targetPiece, int side)

to

private bool checkPiece (Transform targetPiece, int side)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top