Home > Software engineering >  Passing Gameobject throught class in Unity
Passing Gameobject throught class in Unity

Time:09-22

im trying to make a card game. There is something I can't understand:

I have a class named HandManagement that has a list of GameObject and a method AddToHand that add to a list (the hand) a gameobject passed through variable (bringing in hand)

I have a Tile GameObject on the screen with a script that, when collides with mousedown: the variable hand of HandManagement type is called with method AddToHand to add that gameobject to hand (AddToHand(this.gameobject)

When I try unity tells me that the object doesnt exist.. Why?

Thank you

Tile Class:

    {
        m_ObjectCollider.isTrigger = true;
    
        tileInHand.PickTile (tileName);

        

HandManagement Class:

    public GameObject tile;
    public List<GameObject> hand = new List<GameObject>();

    
    public void PickTile(string pickedTile)
    {
    
        Debug.Log ("picked");
        tile = Instantiate (tile);
        tile.transform.SetParent (transform, false); //i put it in a grid of hand card

        hand.Add (tile); //I add it to the list of card in hand
    }}

CodePudding user response:

first of all, change the string to a GameObject, then Instantiate it

public void PickTile(GameObject pickedTile)//change it from string to gameobject
{

    Debug.Log ("picked");
    tile = Instantiate (pickedTile);//instantiate the picked tile.
    tile.transform.SetParent (transform, false); 

    hand.Add (tile);
}}

now tile holds the GameObject "pickedTile" so it will be added to the grid and to the hand.
Next, you need to change the referenced object from a string to a GameObject

tileInHand.PickTile(tileGameObject);

CodePudding user response:

The Instantiate function copies the object tile into tile, this is empty to begin with. Try instantiating a prefab gameobject into the tile, or make sure gameobject tile is never empty (eg. by setting it in the Start()).

https://docs.unity3d.com/ScriptReference/Object.Instantiate.html

  • Related