I am making a game. I just want that When user click on panel in play mode then add a cylinder at this place where mouse is clicked. Also I want to scale up that cylinder along with y vertices till the boundaries of panel.
How we can we do that?
Please Help me
I make cylinder in prefab and attach a script to the camera then assign Prefab object to that script but it is not working. where is the problem??
Code is here
using UnityEngine;
using System.Collections;
public class IntanciateObject : 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;
}
}
}
}
Did you add a physics raycaster to your camera?
In addition, I find the structure of your Update() a bit odd, I would go more like this.
void Update () {
if(Input.GetKey(KeyCode.Mouse0)){
ray=Camera.main.SceenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray,out hit)){
Transform obj=Instantiate(prefab, hit.point, Quaternion.identity);
}
}
}
This way your raycasting only happens when you actually press the mouse.
hit.point is already a vector3 so there’s no need to make a new one like that.
Also Instatiating your prefab as a Transform will work just fine, and it easier to read and less error prone then all that mucking about with unnecessary typecasting.
I also find it easier to read putting this type of thing in something like “OnPointerClick()” which would make your class look like this:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class IntanciateObject : MonoBehaviour,IPointerClickHandler {
public Transform prefab;
public void OnPointerClick(PointerEventData data){
Instantiate(prefab, data.pointerPressRaycast.worldPosition, Quaternion.identity);
}
}
You do still need the raycast component on your camera though. This approch also requires EventSystem and Input modules components (which I put on the camera too).