x


How to access script variables attached to a prefab at runtime in Javascript?

I have a script that generates a grid of prefab tile objects at runtime. I have attached a script to the prefab that contains a single Vector3 to store the grid coordinates of each tile as it's instantiated. How do I access the script component of the prefab from the script instantiating them? I've tried a bunch of different things, but they don't work because a prefab isn't a class.

Thanks for any help.

more ▼

asked Mar 16 '11 at 12:27 AM

BDY gravatar image

BDY
1 1 1 1

I think the prefab to do something like script needs to be in scene so maybe you can take it to the scene then after the script does what you want to save it to your prefab and then you destroy the game object you have in scene.

Mar 16 '11 at 12:41 AM Uriel_96
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

If I understand correctly, you'd do it just like any other object. Once instantiated, you can access the component (script) then anything in it: http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Components.htmland http://unity3d.com/support/documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

The prefab isn't a class, it's an object, but you can get the component (script) off an object, thus stuff in that script.

If that doesn't do it for you, can you post some code?

more ▼

answered Mar 16 '11 at 12:39 AM

DaveA gravatar image

DaveA
26.4k 151 171 256

Ah, that cleared it up, thank you!

basically I did this:

newHex = Instantiate(grassHex, Vector3(curX,curY,curZ), hexRotation); newHex.GetComponent(hexProperties).setCoords(new Vector3(j,i,k));

where hexProperties is the script component attached to the grassHex prefab.

Thanks again!

Mar 16 '11 at 02:26 AM BDY
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3447
x3324
x1669
x1253

asked: Mar 16 '11 at 12:27 AM

Seen: 2818 times

Last Updated: Mar 16 '11 at 12:27 AM