2
\$\begingroup\$

I've looked around for a bit and can't seem to find any way to get a prefab with "Resource.Load" and then to place that object into the world. I'm making a roguelike so when the player enters a room, all rooms around load in. The room to the top would load a random prefab from a list of rooms, check if there's already a room where it wants to go and then PlacePrefab(transform.position, transform.position + 10units); So it would place the prefab 10 units above where the current room is (All code for the rooms will run from a centre object and the prefab would be placed on the centre.)

Thanks in advance for any help :)

\$\endgroup\$
  • 1
    \$\begingroup\$ You're aware of the Instantiate method? \$\endgroup\$ – DMGregory Jan 15 '17 at 17:15
  • \$\begingroup\$ @DMGregory, Oh wow. Thanks. I hadn't seen that in anything but Instanciate(object); where it just made the object on the object that turned it on. If you want to make it an answer then I can give you the tick :) Thanks \$\endgroup\$ – crabcrabcam Jan 15 '17 at 17:20
  • 2
    \$\begingroup\$ I'd recommend that you share your prefab-spawning script as an answer. That will probably be more useful to future users than just a link to the docs. ;) \$\endgroup\$ – DMGregory Jan 15 '17 at 17:22
  • \$\begingroup\$ Alright, I'm working on that now. Thanks for the help :) \$\endgroup\$ – crabcrabcam Jan 15 '17 at 17:31
  • \$\begingroup\$ @DMGregory, Hey. I've been working on the code and finally got to the point of testing it. I've got GameObject newPrefab = Resources.Load("Test Level", typeof(GameObject)) as GameObject; Instantiate(newPrefab, new Vector3(transform.position.x, transform.position.y + 12, transform.position.z), Quaternion.identity); but there's an error. "The object is null". I believe this is because it loads the folder "Test Level" not the prefab by the name. Is there any way to make it load just the file? Thanks :) \$\endgroup\$ – crabcrabcam Jan 15 '17 at 18:35
3
\$\begingroup\$

Thanks to @DMGregory for helping :)

My code for doing this is:

newPrefab = Resources.Load("SizeTest", typeof(GameObject)) as GameObject;
Instantiate(newPrefab, new Vector3(transform.position.x - 8, transform.position.y - 5, transform.position.z), Quaternion.identity);

This loads a 16x10 prefab room above the current room. Change the numbers for where you want it to load. It loads off a middle or centre point where the code is attached to.

Something I didn't realise is that you need to make your files in a "Resources" folder. I thought "Resources" was the same as "Assets". Put everything in there and then the string in the Resources.Load is the file name (No extension)

Hopefully this can help someone doing something similar out :)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.