简体   繁体   English

从同一类C#Unity3d中的另一个方法获取信息

[英]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.. BI是C#和Im的新手,这真的使如何从一个方法中获取信息,然后在同一类的另一个方法中使用该信息感到困惑。

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: 活动结束后,我想使用OnMouseDrag执行以下操作:

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. 但是我似乎无法理解如何从OnMouseDrag中的curPosition中获取信息。

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. 只需移动objectPosition变量,所以它是一个类实例,而不是方法实例。

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. 现在,可以将OnMouseDrag()事件分配给它,并且可以从中读取OnMouseUp事件。

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. 通常,如果您想返回一个值,则您的方法将具有返回类型,但是事件没有返回类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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