0
\$\begingroup\$

I followed this YouTube video but I'm still confused about how the code actually retrieves the value of transform.position.

I can understand the Camera.main.ScreenToWorldPoint code is to transform the screen position to a position in the world based on the camera's view, and it then uses this to update the transform.position as in the private void OnMouseDrag method.

However, I also learnt that since the method is declared as private, the "transform.position" cannot retrieve the value of "transform.position" in each {}bracket.

So how does the value of "transform.position" in private void OnMouseUp, private void Awake get updated, unless I misunderstood the concept?

using UnityEngine;

using UnityEngine.Assertions.Must;

using UnityEngine.SceneManagement;

public class GreenBird : MonoBehaviour

{
    Vector3 _initialPosition;
    private bool _birdWasLaunched;
    [SerializeField]private float _launchPower = 500;

    private void Awake()
    {

        _initialPosition = transform.position;
    }

    void Update()
    {
        if (_birdWasLaunched &&
                 GetComponent<Rigidbody2D>().velocity.magnitude <= 0.1)
        {
            timeSittingAround += Time.deltaTime;
        }

        if (transform.position.y > 10.00 || 
            transform.position.y < -10.00 || transform.position.x > 10 || transform.position.x <-10)
        {
            string currentSceneName = SceneManager.GetActiveScene().name;
            SceneManager.LoadScene(currentSceneName);
        }

       
    }

     void OnMouseDown()
    {
        GetComponent<SpriteRenderer>().color = Color.red;


    }



    private void OnMouseUp()
    {
        GetComponent<SpriteRenderer>().color = Color.white;
        Vector2 directionToInitialPosition = _initialPosition - transform.position;
        GetComponent<Rigidbody2D>().AddForce(directionToInitialPosition * _launchPower);
        GetComponent<Rigidbody2D>().gravityScale = 1;
        _birdWasLaunched = true;


    }

    private void OnMouseDrag()
    {
        Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = new Vector3(newPosition.x, newPosition.y);

    }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Can you expand on what you mean by "However, I also learnt that since the method is declared as private, the "transform.position" cannot retrieve the value of "transform.position" in each {}bracket." ? That doesn't sound like any rule that actually exists in C#. Are you getting this confused with local temporary variables that only exist in the scope where they're declared? \$\endgroup\$
    – DMGregory
    Oct 22, 2020 at 21:10
  • \$\begingroup\$ Thank for your crystal explanation, your example below gave a clear views of what going on and yes, I'm confused it with local temporary variables. \$\endgroup\$
    – chuackt
    Oct 23, 2020 at 3:40

1 Answer 1

2
\$\begingroup\$

It sounds to me like you're confused about the rules for variable scope.

Take a look at this example:

public class Foo {

    // This variable is declared inside the scope of the class.
    // That makes it a "member variable". We allocate one of these variables
    // every time we construct an instance of the class Foo, and it lives
    // and remains accessible as long as that instance does.
    public int memberField;
    
    // This is a method defined inside the scope of the class.
    // We call it a "member function".
    // The "private" means only code in this class is allowed to call the function.
    private void DoSomething() {
    
         // Inside this method, we can read and write to members of the class.
         memberField = memberField + 1;    

         // We can also declare "local temporary variables"
         // to help us do our work inside the function.
         int localVariable = memberField + 1;

         if (memberField + localVariable == 7) { 
             Debug.Log("Seven!");
         }
    }

    private void DoSomethingElse() {
        // Other methods in the class can also read and modify our member variable.
        // They're all accessing the same variable attached to this instance of the class,
        // so changes we make in DoSomething can be seen in DoSomethingElse and vice versa.
        memberField = memberField - 1;

        // But they can't access the temporary variable we declared in DoSomething.
        // localVariable = 3;
        // Uncomment the line above and it will throw an error.
        // We don't have a variable by that name here! (Yet...)

        // We could choose to declare a NEW variable called "localVariable"
        int localVariable = -42;

        // But this has no relationship to the variable in DoSomething.
        // It's a completely different bit of memory that we just called the same name.
    }
}


// We can define a derived class that inherits from the class Foo above.
public class ChildOfFoo : Foo {

    private DoSomethingChildish() {
        // This class's methods are ALSO allowed to use Foo's member variables,
        // because ChildOfFoo IS a kind of Foo, just a specialized version,
        // So it gets all the public or protected members that Foo had.
        // It's just not allowed to use the ones Foo marked as "private".
        memberField = 0;
    }
}

So, coming back to your GreenBird example:

transform is a public member variable of MonoBehaviour (or strictly speaking, its grandparent class, Component), and GreenBird derives from MonoBehaviour.

That means all the functions inside GreenBird are allowed to access its member variables, including transform, and the value is shared between them because they're all looking at the same chunk of memory.

The private in front of our method names just means that other classes aren't allowed to call them... usually. There's a special exception for Unity's MonoBehaviour message functions like Start, Awake, Update, OnMouseDown etc.: Unity looks up these methods using reflection, which works around the normal limitations on who's allowed to call what.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .