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

Selecting between 4 objects script

Discussion in 'Scripting' started by C30N9, Jul 15, 2014.

  1. C30N9

    C30N9

    Joined:
    Dec 11, 2013
    Posts:
    34
    I have four ships in my scene, and I want to give the player the ability to change between these objects by using left/right keys. I also want to make the ship that is selected set its boolean (like "Active") true. Also, I want to make an arrow over follows the selected ship to tell the player which one is selected.

    Any ideas how to make this?

    EDIT: To add on this, the four ships are identical objects with the same scripts, so if one of them have its boolean changed, will it affect the others' boolean values?
     
  2. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Here's a start.
    You could use an array to store your ships then use an integer to cycle between them.
    Code (JavaScript):
    1. var ships : Transform[];
    2. var shipIndex : int;
    3.  
    4. function Update(){
    5. ships[shipIndex].active = true;
    6.  
    7. if(Input.GetKeyDown(KeyCode.RightArrow)){
    8. shipIndex++;
    9. if(shipIndex>= ships.Length){
    10. shipIndex= 0;
    11. }
    12. }
    13. }

    As long as the script is on a totally different gameObject then it wont affect the other booleans.
     
    Last edited: Jul 15, 2014
  3. Crayz

    Crayz

    Joined:
    Mar 17, 2014
    Posts:
    192
    Look into Input functions:
    http://docs.unity3d.com/ScriptReference/Input.html (scroll down to Static Functions)

    Look into Variables:
    http://unity3d.com/learn/tutorials/modules/beginner/scripting/variables-and-functions

    This could be done a number of ways. A simple way to do this would be to create a child gameobject for each ship that is initially disabled, though if your Boolean "Active" is true, the arrow object for that active ship can be enabled to display. Another way would be to create a single arrow gameobject and interpolate its position accordingly.

    Maybe look into the Renderer to hide/show gameobjects:
    http://docs.unity3d.com/ScriptReference/Renderer.html

    The links above and Intense_Gamer94's snippet should get you on the right track.
     
  4. C30N9

    C30N9

    Joined:
    Dec 11, 2013
    Posts:
    34
    Brilliant. However, this line of code looks missing. In C#, how do I change the boolean in the target's script using GetComponent (probably)?
     
  5. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Code (CSharp):
    1. ships[shipIndex].GetComponent<ShipScript>().isActive = true;
    Replace "ShipScript" with the name of the script with the boolean & replace "isActive" with the actual boolean variable.
     
    Last edited: Jul 15, 2014