Question by
stefanplc · Jan 05, 2017 at 12:48 PM ·
c#scripting problemcache
Cache other scripts
Hey guys, I just want to make sure I understand something correctly. The following code is bad practice because GetComponent<> has a significant performance cost so running it several times a second would slow the game down:
void Update() {
ADifferentGameObject.GetComponent<AScriptOnThatGameObject>().SomeString = "SomeValue";
}
But the following is just fine because I first cache the script:
AScriptOnThatGameObject MyScriptOnThatGameObject;
void Start() {
MyScriptOnThatGameObject = ADifferentGameObject.GetComponent<AScriptOnThatGameObject>();
}
void Update() {
MyScriptOnThatGameObject.SomeString = "SomeValue";
}
Is this right? Thanks in advance!
Comment
Best Answer
Answer by UnityCoach · Jan 05, 2017 at 01:22 PM
This is absolutely right ;) You can even do these assignments in Awake ().
Same goes for simple object creation, I usually don't create Vector3 and such in Update, I put them at the class root and assign them in Update, so that they don't get created and garbage collected every frame.