Wednesday, May 4, 2016

c# - How do I instantiate a prefab to a specific coordinate?


I have a prefab called ‘road’. How can I instantiate it (using C#) such that it appears initially at coordinates (5, 5, 5)?



Answer



If you put the prefab into a directory called Resources inside your Assets directory, you'll be able to use the Resources class and its load functionality. This will load a prefab up as a GameObject, which can then be instantiated.


For example:


GameObject myRoadInstance = Instantiate(Resources.Load("road")) as GameObject;

Will create a instance of your "road" prefab in the game world.


You can either set its position by modifying its transform, or you can use the alternate version of Instantiate to specify a position.



GameObject myRoadInstance =
Instantiate(Resources.Load("road"),
new Vector3(5, 5, 5),
Quaternion.identity) as GameObject;

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...