- Home /
Create gameobject on mouse click?
So, basically, My character has to go over a gap by clicking where he wants a cube (called platform) to be created, and than using the cube(s) to parkour over to the over side. Could someone tell me a script or something I could use to make this?
don't understand . you want to create a bridge over a hole so your character can pass it?
Answer by belvita · Dec 03, 2013 at 01:48 PM
ok done for you
attach this script 2 ur camera
create a prefab in unity and attach the object that u want to instantiate to that prefab
then after attaching the code below to camera drag your prefab to the prefab variable on inspector inside this code.
Hope u know this basics.Vote me please VOTE
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
public class instanciateobjectonclick : MonoBehaviour {
Ray ray;
RaycastHit hit;
public GameObject prefab;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
ray=Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray,out hit))
{
if(Input.GetKey(KeyCode.Mouse0))
{
GameObject obj=Instantiate(prefab,new Vector3(hit.point.x,hit.point.y,hit.point.z), Quaternion.identity) as GameObject;
}
}
}
}
This won't change anything functionally, but you might want to reorganize the logic here. $$anonymous$$ake the first if block check for the mouse click, and assign the ray and raycast it. There is no need for this script to be setting and casting the ray every single update call.
I've been trying to get this to work and can't figure out why it won't. With the debug commands I've put in, all I can figure thus far is that the raycast isn't hitting anything. I have the physics and the input conditionals swapped like GerarD suggested and I'm using Get$$anonymous$$ouseButtonDown ins$$anonymous$$d of Get$$anonymous$$ey.
The debug lines I have in for when the mouse button is down will print to the console, but Debug.Log("Ray hit: "+hit.collider.gameObject.name); doesn't print anything to the console so I think that's where the problem is.
Edit: figured it out. I'm using the 2D tools and this method of Raycasting doesn't work in 2D physics.