- Home /
C# Trouble getting object's current position on mouse down.
I have a script which allows the user to instantiate a house object and have that object stick to the mouse position - but so far it can't place the house anywhere, permanently.
I originally tried to get the current transform of my house object within Update but then realised that because of it's nature, the method would be continually well... updating the transform. So I removed that logic and placed it into another method with some success. Pressing the lmb: I can see the object 'blip', which suggests that it's attempting to stay there but the Update function is somehow getting in the way.
Sorry for the comments, they help me think:
public GameObject house;
public GameObject instantiatedHouse;
Vector3 placement = new Vector3();
Vector3 currentPos = new Vector3();
// Use this for initialization
void Start () {
//Load the object into the game.
house = Resources.Load("Medieva_fantasy_house", typeof(GameObject)) as GameObject;
}
// Update is called once per frame
void Update () {
//Cast a ray once per frame from the mouse position to the terrain.
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit))
{
//Determines point of instantiation.
placement = hit.point;
}
//Check once per frame if the house has been instantiated.
//This is a costly way of doing it, not a permenant solution.
if (GameObject.FindGameObjectsWithTag ("MyHouse") != null) {
//Instantiated so set house to raycast's point of contact.
instantiatedHouse.transform.position = placement;
if(Input.GetMouseButtonDown(0)){
instantiatedHouse.transform.position = currentPos;
}
} else {
Debug.Log("House not instantiated.");
}
}
public void InstantiateObject()
{
//This method is called by the button in an OnClick() event.
//Instantiate the object at mouse position along terrain.
instantiatedHouse = Instantiate (house, placement, Quaternion.Euler(0, 0, 0)) as GameObject;
}
public Vector3 CurrentPosition()
{
//Get the current position of the house as a Vector3.
currentPos = instantiatedHouse.transform.position;
//Set the position of the house to equal the position stored in currentPos.
//Hopefully this position will not continually update.
instantiatedHouse.transform.position = currentPos;
/*return the Vector3 which dictates where the object should be placed. currentPos is only invoked when
* user presses lmb down.
*/
return currentPos;
//THIS DOESN'T WORK.
}
}
Like I said, I'm seeing a 'blip' on mouse down and then it continues sticking to my mouse position. This is of course not what I want, so thanks to anyone who tries to help me figure out what's going wrong.