Spawn referencable objects with RayCast

Hello,
i’m new to Unity and the whole scripting-thingy and am currently working on a RTS-Game with the Fury Framework.

I’m looking for a way, to spawn referencable objects with a click on a built terrain.

What i currently use:

public GameObject BuildingType;

[...]

PlaceBuilding(Input.mousePosition);

[...]

public void PlaceBuilding(Vector2 mousePosition)
{
     RaycastHit hit = RayFromCamera(mousePosition, 1000.0f);
     GameObject.Instantiate(BuildingType, hit.point, Quaternion.identity);
}

public RaycastHit RayFromCamera(Vector3 mousePosition, float rayLength)
{
     RaycastHit hit;
     Ray ray = Camera.main.ScreenPointToRay(mousePosition);
     Physics.Raycast(ray, out hit, rayLength);
     return hit;
}

I experience two problems with this:

  1. The building spawns, but always spawns right in the middle of the screen/camera instead of where the mouse is. (I’m using custom-textured mouse-cursors)
  2. How can i add specific scripts to these newly spawned objects (i can only modify them when the game is running) and use them as individual objects?

Thanks in advance!

1 Answer

1

To raycast at mouse position, you ray should be like this:

ray = Camera.main.ScreenPointToRay(Input.mousePosition);

For adding scripts to the objects: GameObject.AddComponent.