- Home /
How do I instantiate an object in an RTS style game?
I'm creating a RTS style game where the player can choose from a toolbar at the bottom to choose what piece they would like to place on the game board. How do I instantiate an object to the position where the mouse is clicked. I know I have to use raycast but I'd like to see how it would work in this instance. Don't worry about creating the toolbar.
Answer by nesis · Jan 15, 2014 at 02:55 PM
Get a reference to the board's collider, and use this (I'll assume your board's collider is assigned to boardCollider
, and that your prefab is assigned to myPrefab
):
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (boardCollider.Raycast(ray,out hit,Mathf.Infinity)) {
Instantiate(myPrefab,hit.point,Quaternion.identity);
}
It keeps saying object reference not set to an instance of an object. I have a prefab set as myPrefab. I don't understand why it doesn't create a copy of it.
We would need to see your script. $$anonymous$$y guess is that you need to drag and drop your prefab onto the 'myPrefab' variable in the Inspector.