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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Short way to add multiple Vector3s to an Array in C#

Discussion in 'Scripting' started by B-30, Mar 9, 2016.

  1. B-30

    B-30

    Joined:
    Nov 3, 2014
    Posts:
    28
    Hi All,
    What is the short way of doing this?

    Code (CSharp):
    1.  
    2. Vector3[] positions = new Vector3[3];
    3. void Start() {
    4. positions [0] = new Vector3 (1, 0, 0);
    5. positions [1] = new Vector3 (0, 0, -1);
    6. positions [2] = new Vector3 (0, 0, 1);
    7. }
    8.  
    Any help much appreciated!
     
  2. Darholm

    Darholm

    Joined:
    Mar 1, 2016
    Posts:
    63
    You could try something like :
    Code (CSharp):
    1. Vector3[] positions = new Vector3[3]{new Vector3 (1, 0, 0),new Vector3 (0, 0, -1),new Vector3 (0, 0, 1)};
    In a more global way, you can initialize an array with :
    Code (CSharp):
    1. Type[] array = new Type[nb elements]{element0, element1,....};
     
    Kiwasi likes this.
  3. B-30

    B-30

    Joined:
    Nov 3, 2014
    Posts:
    28
    Thanks Darholm.
    Code (CSharp):
    1. QualitiesOfDarholm.Add("Awesomeness");
    :)
     
  4. Darholm

    Darholm

    Joined:
    Mar 1, 2016
    Posts:
    63
    You're welcome ;)
     
  5. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,200
    You don't to specify the number of elements, or the type. This does the same thing:

    Code (csharp):
    1. Vector3[] positions = {
    2.     new Vector3(1, 0, 0),
    3.     new Vector3(0, 0, -1),
    4.     new Vector3(0, 0, 1)
    5. };
     
    Kiwasi likes this.
  6. B-30

    B-30

    Joined:
    Nov 3, 2014
    Posts:
    28
    So it does, thanks Baste!