iman_sh
iman_sh

Reputation: 430

Unity3d - Call public static variable performance

I want to know if I call a public static variable from another script in Update or FixedUpdate function , is that affect on performance ?

something like :

[RequireComponent(typeof(Rigidbody))]

public class CC : MonoBehaviour
{
    //Components
    public static Rigidbody rigidbodys;

    void Awake()
    {
        rigidbodys = GetComponent<Rigidbody>();
        rigidbodys.freezeRotation = true;
        rigidbodys.useGravity = false;
        rigidbodys.isKinematic = true;
    }
}

And in another script :

void FixedUpdate()
{
      if(CC.rigidbodys.velocity > 1)
          {
            DoSomething();
          }
}

If I use this way, will reduce performance or not?

Upvotes: 0

Views: 895

Answers (2)

Game Generator
Game Generator

Reputation: 153

That looks very good. In your Fixed Update you only access the rigibody (which is set once in awake) and this is cheap. You can also make a normal public Rigidbody rigbdy and pass your configured gameobject in the inspector. Then you can pass the content to your static Rigidbody. So you clean up the Awake.

    void Awake()
    {
        rigidbodys = ridbdy;
    }

From perfromance side (> means better): static > Singleton Pattern > GetComponent/FindObject

Upvotes: 2

Boris Li
Boris Li

Reputation: 73

As long as you keep you getComponent() out of update(), it would be faster than, for example, calculating the velocity in the other script.

Upvotes: 0

Related Questions