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

Storing GameObject In Multitype Array Object

Discussion in 'Scripting' started by Phocus, Jul 9, 2015.

  1. Phocus

    Phocus

    Joined:
    Jul 6, 2015
    Posts:
    18
    I am trying to build a 2d array of multiple data types

    [Int],[Int],[Int],[GameObject]

    So I used this
    static Object[,] LetterTiles = new Object[64,4];

    Then I can store the game object like this
    LetterTiles[1,3] = new GameObject("MyLetterTile");

    I cant find a way to set properties directly from the array, without first copying the GameObject out of the Array to a new Variable.

    These Don't work:
    (GameObject) LetterTiles[1,4].AddComponent<SpriteRenderer>();
    LetterTiles[1,4](GameObject).AddComponent<SpriteRenderer>();
    LetterTiles[1,4].AddComponent<SpriteRenderer>();


    This does but I am hoping there is a better way.
    GameObject currentWorkingLetter;
    currentWorkingLetter = LetterTiles[1,4];
    currentWorkingLetter.AddComponent<SpriteRenderer>();
    LetterTiles[1,4] = currentWorkingLetter

    When I copy currentWorkingLetter = LetterTiles[1,4]

    Does that create a duplicate Game Object in the Scene?;
    Is there a better way to do this?
     
  2. magnite

    magnite

    Joined:
    Dec 12, 2012
    Posts:
    125
    No that does not create a duplicate object in the scene, but it does create a seperate variables so any changes wont effect the GameObject in the array. You should be able to do the following line to quickly access and change the GameObject in the Array without a new variable:

    Code (csharp):
    1. ((GameObject)LetterTile[1,4]).AddComponent<SpriteRenderer>();
    This is different than what you have because you are converting it to a GameObject after trying to add the SpriteRenderer. Putting it in the parenthesis allows the typecast to happen before you call AddComponent.
     
  3. Phocus

    Phocus

    Joined:
    Jul 6, 2015
    Posts:
    18

    Thank you !

    Also, Afterward I found out that you can not store type [int] in type [object]