Search Unity

Sorting an array of gameObjects, with js

Discussion in 'Scripting' started by ricardHagerman, May 26, 2014.

  1. ricardHagerman

    ricardHagerman

    Joined:
    May 26, 2014
    Posts:
    3
    #pragma strict


    var segments : GameObject[];
    private var words : int;


    function Start () {

    bullets = 0;

    // finds all gameObjects with the tag bullet

    segments = GameObject.FindGameObjectsWithTag("bullet");

    // if all gameObjects with the tag "bullet" is named "0", "1", "2", .... then this will sort the gameObjects in asending oreder, provided that the number of gameObjects with the tag bullet is 10. (you could use segments.lenght)

    for(var i = 0; i < 10 - 1; i++){
    for(var j = 10 - 1; j > i; j--){
    var temp;
    if( parseInt(segments[j].name) < parseInt(segments[j - 1].name)){
    temp = segments[j];
    segments[j] = segments[j - 1];
    segments[j - 1] = temp;
    }
    }
    }
    }

    function Update () {

    //Starts an animation for one bullet (starting with bullet 0) when the "s" key is presed by activating an transition in the bullets animator witht the trigger "bom". The same trigger is used for all bullets.

    if(bullets < 10){

    if(Input.GetKeyDown("s")){

    Debug.Log(segments[worbullets].gameObject.name);

    segments[bullets].gameObject.GetComponent(Animator).SetTrigger("bom");

    words ++;

    }

    }

    }
     
    Last edited: May 26, 2014
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401