Gigab0rt
Gigab0rt

Reputation: 302

Access attributes of class attached to GameObject

So I have a prefab with a c# script attached (ScriptA), then I instantiate a number of GameObjects of this prefab from another script (ScriptB).

public class ScriptA : MonoBehaviour {
    public int pos;

...

public class ScriptB : MonoBehaviour {

    public GameObject prefab;   
    GameObject [] all;

... And then at some point objects are created:

    for (int i = 0; i < 10; i++){
       Vector3 v = new Vector3(i, 0, 0);
       v = v * 3;
       GameObject newObject;
       newObject = GameObject.Instantiate(prefab, v , Quaternion.identity);
       all[i] = newObject;
    }

So my question:

Are instances of ScriptA created with each prefab Object? And if so, how do I access them and their attributes?

Upvotes: 1

Views: 1597

Answers (1)

Heisenbug
Heisenbug

Reputation: 39164

If ScriptA is attached to the instantiated prefab, you can get a reference from it using GameObject.GetComponent method, for example:

ScriptA  aInstance = newObject.GetComponent<ScriptA >();
int p = aInstnace.pos;

the you can call access the desired properties or methods on ScriptA instance (aInstance).

Upvotes: 4

Related Questions