x


How can I get a reference to a gameobject in my C# script?

I currently have the following:

public List<GameObject> myWalls;

And in the unity property inspactor script definition area I have:

My Walls
Element 0: Wall1
Element 1: Wall2
Element 2: Wall3

Now I would like to create these objects in code as I need to pass into them some parameter. How can I do this in code? In other words how can I initialize the myWalls list with the gameobjects Wall1, Wall2 and Wall3?

more ▼

asked Aug 18 '12 at 08:29 AM

rscholey gravatar image

rscholey
40 3 8 11

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first
var myWall1=Instantiate(myWalls[0],somePosition,someRotation);

//Do something with myWall1....
more ▼

answered Aug 18 '12 at 08:36 AM

OperationDogBird gravatar image

OperationDogBird
1.1k 1 9 15

thanks for taking the time to reply but I am not sure this answer is what I am looking for. What I would like to do is eliminate the need to define Element 0, 1 and 2 in the inspector. I want to do everything in code.

Something like

myWalls[0] = ??; myWalls[1] = ??; myWalls[2] = ??;

Aug 18 '12 at 08:40 AM rscholey

You can use Resources.Load or LoadAll and cycle through the elements to fill your list

Object[] arr = Resources.LoadAll("SomethingAtSomePath");
for(i:int=0;i<arr.Length;i++)myWalls.Add(arr[i]);

maybe something like that?

I normally type unityscript so i apologize if i made some mistakes in syntax... i think it may be system object (lower case) rather than the JavaScript equivalent Uppercase Object. and you can use a for each type loop

for( obj in arr ) myWalls.Add( ( DownCast ) obj );

Sorry my C# is rusty

Aug 18 '12 at 08:46 AM OperationDogBird

Thanks. I will try this out and mark if it worked okay which I think it will :-)

Aug 18 '12 at 08:49 AM rscholey
(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:

x10
x8

asked: Aug 18 '12 at 08:29 AM

Seen: 176 times

Last Updated: Aug 18 '12 at 08:55 AM