Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Make a clear getComponent

Discussion in 'Scripting' started by Dzxyan, Jun 10, 2014.

  1. Dzxyan

    Dzxyan

    Joined:
    Sep 23, 2013
    Posts:
    167
    As a example i get the component like this,

    Code (CSharp):
    1.  
    2. gObject01[i].GetComponent<aScript>().fuctionA = intNumber;
    3. gObject02[i].GetComponent<aScript>().fuctionA = intNumber;
    4. gObject03[i].GetComponent<aScript>().fuctionA = intNumber;
    5. gObject04[i].GetComponent<aScript>().fuctionA = intNumber;
    6. gObject05[i].GetComponent<aScript>().fuctionA = intNumber;
    7.  
    and more...

    i need define the intNumber gObject01 is same with gObject02,
    i call every time like this

    Code (CSharp):
    1.  
    2. if(gObject01[i].GetComponent<aScript>().fuctionA == gObject02[i].GetComponent<aScript>().fuctionA)
    3. {
    4. //something happen
    5. }
    6.  
    and gObject02 will compare with gObjects01
    and more and more...

    for a function still can acceptable but if i use it in multiple function i think it a bit hard code,
    can i optimize it become just like

    Code (CSharp):
    1.  
    2. void Start(){
    3. GameObject g01 = gObject01[i].GetComponent<aScript>()
    4. GameObject g02 = gObject02[i].GetComponent<aScript>()
    5. }
    at void Start() function;
    and just use
    Code (CSharp):
    1.  
    2. if(g01.functionA  == g02.functionA)
    3.  
    like that?
    i try like that but didn't work, any help please?
     
  2. ElvisAlistar

    ElvisAlistar

    Unity Technologies

    Joined:
    Oct 2, 2013
    Posts:
    226
    You need to declare g01 and g02 in the class outside of the Start() method. Short version: make g01 and g02 global variables and it should work.
     
  3. Dzxyan

    Dzxyan

    Joined:
    Sep 23, 2013
    Posts:
    167
    Actually i cant declare it on global because my GameObject is multiple [] , i just wanna declare the active one.
     
  4. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    Code (csharp):
    1. // This is wrong, because aScript is not a GameObject.
    2. GameObject g01 = gObject01[i].GetComponent<aScript>();
    3. // Declare g01 as type aScript, since that is what GetComponent<aScript>() returns.
    4. aScript g01 = gObject01[i].GetComponent<aScript>();
    5. g01.someFunction();
     
  5. Dzxyan

    Dzxyan

    Joined:
    Sep 23, 2013
    Posts:
    167
    Thanks!
    That what i miss for it,
    i forgot it is a script,
    Problem solve!