- Home /
Get Variable From A Script Attached To a Prefab
Hi, all! I like to make my scripts modular... I like to make one script that works for all instances and objects that might use it so that I simply have to set up parameters for it. That's why I love Unity ;)
I have a script attached to a prefab. Four different prefabs will have this script, but the variable 'x1' in each prefab will be different. From a script attached to the main camera, I would like to get the variable 'x1' from the script from Each Prefab. I do not know how to do this, though, because the prefab may not be spawned. I just need it to automatically reference the prefab, and then the script attached to it as a component, and then get the variable for each of the four. How would I go about doing this?
Thanks- YA. (Please tell me if I made this over complicated :P )
Answer by jahroy · Dec 02, 2011 at 02:40 AM
I think the answer to your question depends on how your prefabs exist in your scene in relation to the other objects.
Will they have a name that you can predict?
How will they be created?
Is there a reason why you can't attach your prefabs to your camera script directly?
It's hard to say (without knowing a little more about your scenario), but I would normally say the easiest way would be the last option.
If the script with the x1 variable is a file named SomeFunkyScript.js, you can add the following to the top of your camera script (the script that is attached to your camera):
/* this can be any object with a SomeFunkyScript attached to it. */ /* you can assign it in the Inspector by dragging and dropping */
public var funkyObject : SomeFunkyScript;
/ you can now reference funkyObject's variables and functions /
function Update () { if ( funkyObject != null ) { Debug.Log("Funky Object x1: " + funkyObject.x1); }
else {
Debug.LogWarning("Funky Object is null.");
}
}
.
.
.
.
Better yet, you could declare an array of SomeFunkyScript objects like this:
public var funkyObjectArray : SomeFunkyScript [];
function Update () { var count : int = 0;
/* print x1 value for each item in the array */
for ( var thisFunk : SomeFunkyScript in funkyObjectArray ) {
Debug.Log("Item " + count + " x1 value: " + thisFunk.x1);
count ++;
}
}
This would allow you to drag and drop multiple objects onto the slot in the Inspector named Funky Object Array.
You can drag any GameObject onto the slot that has a SomeFunkyScript script attached to it.
Hope this helps.
Answer by Youngapprentice · Dec 02, 2011 at 02:47 AM
Thank you. Yes, every prefab is attached to the camera, because I use the variable to instantiate this. Will try it out and say what happens! Thanks! (hopefully :P)- YA
Answer by Youngapprentice · Dec 02, 2011 at 03:14 AM
Thank you much! It worked out just fine. Works perfectly, actually! ;)
Your answer
![](https://koobas.hobune.stream/wayback/20220613061707im_/https://answers.unity.com/themes/thub/images/avi.jpg)