Search Unity

Keep components as fields inside a script?

Discussion in 'Scripting' started by mahdiii, Sep 14, 2017.

  1. mahdiii

    mahdiii

    Joined:
    Oct 30, 2014
    Posts:
    856
    Hi all. Suppose we have two scripts like ScriptA and ScriptB for obj1.
    Then ScriptC for obj2 has an array of obj1 and needs to access to ScriptA and ScriptB objs1.
    We can write obj1.GetComponent<ScriptA>() and obj1.GetComponent<ScriptB>()
    or can write ScriptA scriptA=obj1.GetComponent<ScriptA>() and scriptA.scriptB, if we have
    Code (CSharp):
    1. public class ScriptA:Monobehaviour {
    2. ScriptB scriptB;
    3. }
    4.  
    but it creates extra depandancy and coherence. How can we reduce these coherences?
    Do we keep the references of components only when we need them inside the script?
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Short answer is: yes - don't junk up your behaviours with references they never use (the compiler even warns you about this).
     
    mahdiii likes this.