Search Unity

need help with my code

Discussion in '2D' started by PersianKiller, Jul 16, 2018.

  1. PersianKiller

    PersianKiller

    Joined:
    Jul 16, 2017
    Posts:
    132
    Code (CSharp):
    1.  
    2.  
    3.  
    4. public int[] w;
    5.  
    6. void Start(){
    7. w=new int[5];//so it will set size of w to 5 at the start
    8. }
    9.  
    10.  
    11.  
    but i want to do it via a function like this
    Code (CSharp):
    1.  
    2.     public void setSizeOfArrayInt(int[] varName,int size){
    3.         varName= new int[size];
    4.     }
    5.  
    but it's not working ,how can i fix it?

    setSizeOfArrayInt(w,5);
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Passing w into a function only passes the value through in a temporary local variable 'varName'.

    If you want to assign a variable outside of the function scope as a parameter, you need to use the 'ref' or 'out' keywords for the parameter, to pass w as a reference.

    Use 'ref' if the variable is initialized outside the function, use 'out' if the variable should be initialized inside the function.

    Code (CSharp):
    1. private void Start()
    2. {
    3.     int[] w;
    4.     setSizeOfArray(out w, 5);
    5. }
    6.  
    7. public void setSizeOfArray(out int[] varName, int size)
    8. {
    9.     varName = new int[size];
    10. }
     
    PersianKiller likes this.