So I have a relatively simple system set up now thanks to the answers here and tutorials I found elsewhere where I can click a button or press a key and my ‘building’ prefabs will spawn onto the floor where my mouse cursor is.
I just have one problem though, I don’t know how to make my instantiated objects stick to the cursor like a blueprint in a lot of RTS and City Builder games you see.
This is a classic example of what I’m talking about and uses a Unity game too.
How would you get the blue textured object to attach itself to the mouse cursor permanently? Would it be a parent? Or something else? Right now I can only get my objects to instantiate onto a surface but I’d really like to be able to drag an object around like in this game and of course keep the object on the surface that the mouse cursor is hovering over.
It’s generally not a parent. You need to use raycasting to find where the mouse cursor intersects the ground, for starters. As for making it stick where the cursor is as it moves, I usually do something like this (in its most basic possible form):
private GameObject holdingThing;
//called by a "Create" button or whatever
public void SpawnAndHoldThing(GameObject thingPrefab) {
holdingThing = Instantiate(thingPrefab) as GameObject;
}
void Update() {
if (holdingThing) {
RaycastHit rchit = new RacyastHit();
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out rchit, 1000f) ) {
holdingThing.transform.position = rchit.point;
}
if (Input.GetMouseButtonDown(0) ) {
//if needed, 'initialize' any scripts on holdingThing here
holdingThing = null;
}
}
Naturally, you will want to add some more logic to this (e.g. determining whether or not its current location is a valid placement). I also usually don’t use the GameObject directly, but rather use a ‘BuildableObject’ component that can hold more information and functions. This is just a framework to get you started.
Thank you! I already have a raycast attached to the object itself that I’m using so it can find the ground so that’s taken care of, I’ll try this out and see how it works.
I see what you’re on about though, I take it you need it to be instantiated on the ground and THEN there’s a second raycast constantly updating the position of the object that’s being instantiated to the mouse position, that’s the extra bit that I wasn’t thinking about, I’ve just been instantiating the object to the ground and then that’s it so no wonder nothing was happening.