Search code examples
c#unity-game-enginegameobject

How to access the properties of any created Game Object from another script Unity C # 2D


I have instantiated multiple game objects like this part of the code:

GameObject newCard = Instantiate(CardPrefab, new Vector3(x, y, z), transform.rotation);

x,y and z being parameter so I could spawn the objects in different positions.

My question is how could I access the name of the Game objects or the properties from another script. Each of my game objects has a property which gives it a value.

In another script I want to add the values of all objects but I am not sure how to access the objects from another script to get their name and values.

Thanks for the support.


Solution

  • If you are trying to access the GameObjects name, with the way you have done it, it is as simple as saying:

    newCard.name = "The new name!";
    

    if you are trying to access the properties of a script that you are assigning to this specific GameObject it would be best to do something like this:

    public class card : MonoBehavior {
        public int faceValue;
        public int suitValue;
        //  or whatever else you need in your card...
    
    }
    

    In your spawner Object:

    public class Spawner : MonoBehaviour {
        public Card cardPrefab;  // Instantiate will spawn this correctly and return the attached component to you.  
                                 // Less prone to error for this specific script since we are expecting a prefab
                                 // with a card script attached.
    
        // Spawn Method
        void SpawnCard(float x, float y, float z, int value, int suitValue)
        {
            Card newCard = instantiate(cardPrefab, new Vector3(x, y, z), transform.rotation);
            newCard.gameObject.name = "someName";
            newCard.faceValue = value;
            newCard.suitValue = suitValue;
        }
    
    }
    

    To access all gameobject with this script you can either create some form of manager that tracks them all as you create them(Preferred method),

    or...

    You could use GameObject.FindObjectsOfType<Card>() Which is incredibly slow as you get bigger scenes, if you have a small scene then it is fine.