Question by
GabiM · May 28, 2017 at 03:14 PM ·
instantiatemouse position
Instantiate object at mouse position
Hi! I want to instantiate an object at mouse position so I've made this script and I'm getting the following error:
NullReferenceException: Object reference not set to an instance of an object SetPlant.TaskOnClick ()
public class SetPlant : MonoBehaviour {
public GameObject plant;
void Start () {
Button button = GetComponent<Button>();
button.onClick.AddListener(TaskOnClick);
}
public void TaskOnClick()
{
var mousePos = Input.mousePosition;
Vector3 objectPos = Camera.current.ScreenToWorldPoint(mousePos);
Debug.Log("test");
Instantiate(plant, objectPos, Quaternion.identity);
SetPosition();
}
void SetPosition()
{
var mousePos = Input.mousePosition;
var objectPos = Camera.current.ScreenToWorldPoint(mousePos);
plant.transform.position = objectPos;
if (Input.GetButtonDown("Fire2"))
{
Destroy(plant.gameObject);
}
else if (Input.GetButtonDown("Fire1"))
{
RaycastHit hitInfo = new RaycastHit();
Physics.Raycast(Camera.main.ScreenPointToRay(mousePos), out hitInfo);
if (hitInfo.collider.gameObject.tag == "SetableArea")
{
plant.transform.position = new Vector3(hitInfo.transform.position.x, hitInfo.transform.position.y + 1f, hitInfo.transform.position.z);
}
}
else SetPosition();
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612122840im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Firing to a mouse position 0 Answers
Why are my bullets instantiating as children of the player? 0 Answers
Instantiate at touch.position 0 Answers
Unable to delete instance of GameObject 0 Answers
Destroy Instantiate is not working 0 Answers