- Home /
Loading Resources from folder in Project to Hierarchy
It sounds like a really simple question, but it's a problem I'm having and I've been unable to find a response yet.
I'm currently doing a few tests to set up a tower defence game eventually - and I've put a test prefab called "Cube" in a folder called Enemies, in project view. I have tried using the following code:
object=Resources.Load("Cube");
transform.position.x=Random.Range(-4.5,4.5);
obj=Instantiate(object,transform.position,transform.rotation);
It's attached to a spawner object which will move to a random x location and create the Cube prefab there. It's quite obvious that the Cube part is the problem - and that's definitely its name.
However, it's in a folder called Enemies, which I assume is the problem. At this point, it's not a specific problem that I have to have everything in folders - but sooner or later this organisation will be essential so I may as well nail it now.
Could anybody please help me with how to reference an object in a folder?
On a side note, how would I have it let me drag the prefab in via the inspector? This would probably be a much easier method.
Thanks very much, Callum.
Answer by Mike 3 · Jul 13, 2010 at 01:25 PM
You must put the items inside the Resources folder (or a subfolder of it)
In your case, /Project/Assets/Resources/Cube will be loaded by Resources.Load("Cube")
If you want to load something in a subfolder of that, it'd be Resources.Load("SubFolder/Cube")
To drag an object into the inspector (which is in fact easier), you would just make a public variable for the type of object
In your case:
c#
public GameObject cube;
js:
var cube : GameObject
You'd then just drag and drop into the inspector
Note - you don't have to make it GameObject, it can be any type you have in your prefab, including scripts, AudioSource, etc etc
Aah yes, I think I recall reading about the resources folder - forgot about that. Thanks!
I've tried the drag and drop method of exposing the variable, but it doesn't seem to show in the inspector.
I've attached this: function update(){ var enemy : GameObject; transform.position.x=Random.Range(-4.5,4.5); obj=Instantiate(enemy,transform.position,transform.rotation); }
to the spawner, but it doesn't seem to show up in the inspector as a variable.
Thankyou very much for your response though.
Aha. $$anonymous$$oved the variable out of the function, and it's shown up. Still figuring out what's wrong with the script itself because it won't work - but the variable is exposed now. :)
Your answer
Follow this Question
Related Questions
How to properly load textures? 2 Answers
Can't drag assets from Project folder to Hierarchy/Scene 2 Answers
Unable to Drag and Drop from the Project pane into the Hierarchy pane in Unity 5.4.0b22 0 Answers
which one of the panels in unity has effect on the size of the project? 0 Answers
How to auto-navigate project hierarchy to asset by clicking in inspector? (Doesn't work anymore.) 1 Answer