You have developed many games for your clients, and during the development process, we need to pick and place an object many times.
This is a beginner's blog to make you learn how to pick and place an object at the mouse position in the game.
We can instantiate multiple clones of given Game Object or Object Prefab using the function:
Instantiate (Object Target, object’s position, object’s rotation) Or
Instantiate (Object Target)
If you want to instantiate a game object at a position that was clicked on the surface, you have to first find the world point of the tabbed place.
We Can Do This Using Two Methods:
If you are making shooting game, to find where the object is hit can use hit.point
You can use mouse position that can easily be converted into world position.
Here, using mouse position we will place the object in the world position. To get the mouse position, we can use the function:
Input.mousePosition
This function returns the position that is in pixels. So, we need to convert it into the World position.
To convert the mouse position into the World position, we will use the function:
Camera.Main.ScreenToWorldPoint
This function will convert the screen to transform the position into the World position. Now you can use this position to place objects at where mouse click is done.
Now, by using this function we will create a short demo of it.
Open unity and go to File >> New Project
Give the name of the project what you want and select 2D from the drop-down menu and press create button.
Create a scene with main camera and a Game Object, which is used as a target Object for making multiple clones of it.
You can also create a canvas and a panel and set any image as a background. (Optional)
Here, an image can also be used as a target object. For this, we need to convert image into 2D sprite and after converting we can use that image as a Game object in the scene.
Now, Create an empty game object name with “Object Manager” and Apply this Below C# Script on this game object and pass the reference of the target object which we want to instantiate.
Here, Left Mouse Button is used to Place Object. While placing the object on space, keep pressing Left Mouse Button Down to move the position of the object.
This basic guide will help you in-game development with Unity. And you will be able to create the best game applications for your clients.
COO of Vasundhara Infotech, a leading Software development company in the USA. His technological interests has helped the company in making useful decisions.
Sign Up to our newsletter to get latest updates staight in your inbox.
Vasundhara respects your privancy. No Spam!
Sign Up to our newsletter to get latest updates staight in your inbox.
Vasundhara respects your privancy. No Spam!