Search Unity

Need help with accessing variables

Discussion in 'Scripting' started by Treva, Aug 31, 2009.

  1. Treva

    Treva

    Joined:
    Aug 26, 2009
    Posts:
    17
    I'm having problem with access variables that are in an array of GameObjects:

    var marbles : GameObject[];
    var marble1;

    function Awake() {
    marble1 = gameObject.Find("/marble1");
    marbles = new GameObject[10];
    marbles[0] = marble1;

    marble1.colour = 1; //This is ok
    marbles[0].colour = 1; //This causes an error, but I have to use it because I'm swapping the positions around
    }

    The error returned was: 'colour' is not a member of 'UnityEngine.GameObject'. Any idea how I can solve this? Thanks.
     
  2. Timmer

    Timmer

    Joined:
    Jul 28, 2008
    Posts:
    330
    Check:
    http://unity3d.com/support/documentation/ScriptReference/GameObject.html

    No colour in GameObject!

    What you're probably looking for is the color that belongs to Material which can be accessed via the renderer.material:

    Code (csharp):
    1. marbles[0].renderer.material.color = Color.red
    Also I don't think there's an int to Color conversion so you'll want either a pre-defined color name or one of (r,g,b) or (r,g,b,a) constructors.

    Code (csharp):
    1. marbles[0].renderer.material.color = Color(1.0, 0.0, 0.0)
     
  3. Treva

    Treva

    Joined:
    Aug 26, 2009
    Posts:
    17
    Thanks for the reply, but I think you have misunderstood the situation. colour is a variable declared in another script, which acts like an enum.
     
  4. Ashkan_gc

    Ashkan_gc

    Joined:
    Aug 12, 2009
    Posts:
    1,124
    you should add a colour property to you object and then you will be able to use it.
    you should create an script that has colour enum or property in it and then add that script as a component to any gameobject that wants to use it and then you will be able to use colour property

    also there is another approach that i did not tested but you can make a custom class inherited from GameObject and then create instances of that class instead of GameObject and define colour in that class.
    i did not test this approach but i think it should work
     
  5. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    If your script is just an ordinary one (with a class derived from MonoBehaviour) attached to each of the objects in the marble array, then there is an extra step you need to take. The script is actually a component added to the GameObject, rather than equivalent to the GameObject itself. You can find a script attached to a GameObject using the GetComponent method. If the marble script were called MarbleController, then you'd do something like:-
    Code (csharp):
    1. marble1 = gameObject.Find("/marble1");
    2. scriptOnMarble1 = marble1.GetComponent(MarbleController);
    3.  
    Once you've got the script component, you can access its variables as normal.