简体   繁体   中英

Get information from another method in the same class C# Unity3d

BI pretty new to C# and Im really confused how to get information from a method, and then use it in another method in the same class..

So far I got this script

public class DragDropBehaviour : MonoBehaviour 
{
private Vector3 screenPoint;
private Vector3 offset;

void OnMouseDown()
    {
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
        Debug.Log("Clicked "+gameObject.name);
    }

public void OnMouseDrag()
    {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint)+offset;
            transform.position = curPosition;
            var objectPosition = curPosition;
        }
}

After the event and my with OnMouseDrag I want to do something like this:

void OnMouseUp()
        {
            Debug.Log("GameObject is now at "+onMouseDrag.objectPosition);  
        }

But I can't seem to understand how to get out the information from the curPosition in my OnMouseDrag.

How can I solve this in a simple and easy way?

Just move the objectPosition variable, so it's a class instance instead of a method instance.

public class DragDropBehaviour : MonoBehaviour 
{
    private Vector3 screenPoint;
    private Vector3 offset;

    private Vector3 ObjectPosition;

Now the OnMouseDrag() event can assign to it, and the OnMouseUp event can read from it.

public void OnMouseDrag()
{
    Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint)+offset;
    ...
    ObjectPosition = curPosition;
}

void OnMouseUp()
{
    Debug.Log(string.Concat("GameObject is now at ", ObjectPosition));
}

Normally, if you wanted to return a value then your method would have a return type, but events don't have return types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM