- Home /
How can i show a preview of a Prefab in the world before actually spawning it?
I am trying to create a skill where a player can spawn a GameObject in the world once a skill bar is filled. Before they spawn it, i want them to be able to see a preview of it and how it would look in the world, similar to the preview below.
I want to be able to show this object where the player is aiming. I'm ray casting from the camera to the centre of the screen and then getting the co-ordinates of the hit.point. I know how to Instantiate prefabs at that location, but don't know how to show a preview of it beforehand.
Any help would be appreciated as i'm new to Unity and these forums.
Answer by Yuvii · Oct 13, 2017 at 12:51 PM
Hey,
Actually, the preview is an instantiated object itself. just make it follow the hit.point position, and when the player clicks, instantiate the real prefab and destroy the preview (there's a lot of possibilities, this is just one, but the 'preview' is an object like all the others).
Hope that helped :)
That helped, thanks!
However, i'm now having problems with the preview object itself. The object spawns at the hit point, but then does a weird thing where it seems to launch itself into the camera. Any ideas on the problem? I have tried to add a rigidbody but still having the same problem.
$$anonymous$$y code is here just in case i'm doing something wrong. I'm finding the object with tag as i don't know how to find a specific instance of a prefab, but i can figure that out later.
Vector3 rayOrigin = camera.ViewportToWorldPoint (new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Physics.Raycast (rayOrigin, camera.transform.forward, out hit, range))
{
//Debug.Log (hit.point);
if (spawned == 0) {
Instantiate ($$anonymous$$inionNotSpawned, hit.point, Quaternion.identity);
spawned = 1;
}
}
if (spawned == 1)
{
Debug.Log ("1");
//GameObject.FindWithTag("$$anonymous$$inionNS").GetComponent<Rigidbody>().$$anonymous$$ovePosition (hit.point);
GameObject.FindWithTag("$$anonymous$$inionNS").transform.position = hit.point;
}
It's because the raycast collides with the preview object
Simply disable the preview's collider and it should be okay !
Anyway you still can optimize a bit more and store your instantiated preview in a variable ins$$anonymous$$d of looking for it at every frame
GameObject $$anonymous$$inionNS = null; /*(have to be outside the Update() )*/
Vector3 rayOrigin = camera.ViewportToWorldPoint (new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Physics.Raycast (rayOrigin, camera.transform.forward, out hit, range))
{
//Debug.Log (hit.point);
if (spawned == 0) {
$$anonymous$$inionNS = Instantiate ($$anonymous$$inionNotSpawned, hit.point, Quaternion.identity);
spawned = 1;
}
}
if (spawned == 1)
{
Debug.Log ("1");
//GameObject.FindWithTag("$$anonymous$$inionNS").transform.position = hit.point;
$$anonymous$$inionNS.transform.position = hit.point;
}