- Home /
Instantiating gameobject variables (in an array) from a different script
I have 2 prefabs assigned to variables (placed in an array) in a script called test:
var one : GameObject;
var two : GameObject;
static var prefabs = new Array();
prefabs[0]= one;
prefabs[1]= two;
I'm trying to access them with another script as follows:
function Start () {
var instance : GameObject = Instantiate(test.prefabs[0], transform.position, transform.rotation);
}
..but I'm having no luck - the error in the console is "ArgumentOutOfRangeException: Index is less than 0 or more than or equal to the list count."
Can anyone explain what I'm doing wrong?
Answer by BiG · Oct 21, 2011 at 08:42 AM
When you want to use a variable from another script, you have to specify that script first. However, the compiler cannot understand the script that you're trying to "inspect" on its own.
I'm supposing that the first script that you've posted is called "script1", the second one is called "script2", and script1 is assigned to an object called "my_object". So, try this (in script2):
function Start(){
var my_prefab=GameObject.Find("my_object").GetComponent(script1).prefabs[0];
var instance=Instantiate(my_prefab, transform.position, transform.rotation);
}
Thanks for the explanation, I will give this a try.
Can you explain why I'm able to access other script's static numeric variables by simply writing the script's name followed by a fullstop - but in this example I need to first access the gameobject that the script is attached to and then use GetCmoponent?
Well, standing to my knowledge, you have to do as I said in the question when you access a variable in a script, attached to a certain object, from another object. If I'm wrong, I hope to be corrected by anyone.
Your answer
![](https://koobas.hobune.stream/wayback/20220613014723im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Instantiate from array into array? 2 Answers
Save Gameobject in Array 1 Answer
Want replace a current object with one inside array the object being replaced with is prefab 1 Answer
Instantiating a gameObject in an array is not working for me 1 Answer
Referencing an instantiated object with a global variable 0 Answers