- Home /
Question by
Frisk17 · May 30, 2018 at 12:34 PM ·
scripting problemarray
How can I use a variable as length of an array?
I want to set the length of array to a variable (probably int) my imagined code(which certainly doesn't work):
public class NPCscript : Interactable
{
public int Size;
public string[] dialougeSt = string[Size];//HEEEELPPPP!!!
}
Comment
Depending on what you want to do with it, you could just make the integer static.
Answer by Hellium · May 30, 2018 at 12:52 PM
This is not really possible. The only thing I see is to use a setter + OnValidate function
public class NPCscript : Interactable
{
[System.Serializable]
private int size;
public string[] dialogueSt ;
public int Size
{
get { return size ; }
set
{
size = value ;
if( dialogueSt.Length != size )
System.Array.Resize( ref dialogueSt, size );
}
}
void OnValidate()
{
Size = size ; // Calls the setter and update the array length if needed
}
}