Aleks19
Aleks19

Reputation: 47

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.

Upvotes: 2

Views: 5986

Answers (2)

AresCaelum
AresCaelum

Reputation: 1566

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.

Upvotes: 2

Lincoln Doney
Lincoln Doney

Reputation: 86

One thing you could do is to use the GameObject.Find({String gameobjectname}) method, as documented here. This will search through all of the gameobjects and return the gameobject reference to the object with that same name. The issue with this is it only returns one.

Another thing is you could use GameObject.FindGameObjectsWithTag({String tag}). For this one you need to ensure each of the objects have a tag. Based on your object name being card I would set the tag to be Cards. Then you can use the array you get back and do stuff you want with it. That's documented here

Upvotes: 1

Related Questions