- Home /
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:
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)
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!
Answer by dorpeleg · Mar 26, 2013 at 12:25 AM
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.
When i try to add scripts with AddComponent i get the Error, that an object reference is required to access non-static member "UnityEngine.Gameobject.AddComponent(string)". How do i get unique object references each time i spawn a given GameObject? Do i have to make a list of GameObjects in order to achieve this?
The fix for the raycast didn't work... i don't know why. Each time i press esc to cancel the game-mode i notice, that the mouse is automatically placed to the middle of the screen - maybe this has something to do with it. Think i have to check the GUI-Class, where the custom-mouse-cursor is handled.
Your answer
Follow this Question
Related Questions
Best solution for Grid-based building system? 0 Answers
I need help for my RTS Games! 0 Answers
Automatically rotating objects to fit on to others 0 Answers
Unity3D - RTS Game - Instantiate object on buttonclick and make it follow the cursors position 2 Answers
How to Place a Game Object in game(Place a building) 0 Answers