- Home /
Select and save object
I need to be able to click an object in game, and assign a GameObject variable to it, like so:
GameObject Selected;
Selected = (Object Clicked);
But none of the resources I go to seem to work. How do I do this?
Answer by Trevdevs · Sep 24, 2016 at 03:16 PM
Don't worry about assigning the camera it should work just fine :) might have forgotten something let me know though
public Camera camera;
public GameObject Selected;
void Start()
{
camera = Camera.main;
}
void OnMouseOver()
{
if(Input.GetMouseButtonDown(0))
{
Ray ray = camera.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit))
{
hit.collider.gameObject = Selected;
}
}
}
It looks like it should work, but after inserting some prints in various locations, it appears On$$anonymous$$ouseOver isn't called, because "$$anonymous$$ouse Over" is never printed. Any idea why? Here's what I have (excluding the camera stuff):
void On$$anonymous$$ouseOver()
{
print("$$anonymous$$ouse Over");
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
print("Input");
Ray ray = Cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
print("Object set");
ObjectSelected = hit.collider.gameObject;
}
}
}
After changing On$$anonymous$$ouseOver() to Update(), It appears there is another error in the line:
Ray ray = camera.ScreenPointToRay (Input.mousePosition);
It complains that:
NullReferenceException: Object reference not set to an instance of an object
GameController.Update () (at Assets/Scripts/GameController.cs:29)
On$$anonymous$$ouseOver is called anytime the mouse is over a "GUIElement or a Collider" so the object your trying to select must be a 2d gui element or must include some form of a collider.
the reason for the error might be that camera is not being set to the main camera did you include the start function as well?
I set the camera manually and now it works fine. Thanks! Here is the finished code for any people who want to use it:
public Camera Cam;
GameObject ObjectSelected;
void Update()
{
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
Ray ray = Cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
ObjectSelected = hit.collider.gameObject;
}
}
}
Your answer
Follow this Question
Related Questions
How to destroy the clone that I click on Unity 2D 1 Answer
How to click only one once? 0 Answers
How to detect a mouse click on a 2d gameobject? 1 Answer
how to simulate mouse click with fake cursor 0 Answers
I Need help with trees colliding 1 Answer