Search Unity

Getting weird compilation error

Discussion in 'Getting Started' started by linglonglinglong, Mar 17, 2018.

  1. linglonglinglong

    linglonglinglong

    Joined:
    Feb 26, 2018
    Posts:
    20
    I want the camera to move in the forward direction but I want to keep the y position the same. So I wrote this:

    if (walking) {
    transform.position = transform.position + Camera.main.transform.forward * .5f * Time.deltaTime;
    transform.position.y = .5f;
    }

    Yet I got:
    Assets/scripts/cameraControl.cs(25,23): error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position'. Consider storing the value in a temporary variable

    which indicates I can't set transform.position.y? What does it mean??
     
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,141
    There are two ways to create complex data types in C#. One of them is the class you've undoubtedly been using this whole time but the other way to do it is via a struct. This problem is coming from the way structs are treated by C#.

    When you retrieve an object through a property (or an indexer) that is a struct you are given a copy of the object rather than a reference to the object itself. Because it's a copy the actual object you're accessing isn't being stored and therefore can't be modified.

    If you wish to modify the property, you first need to store the copy, then modify it, and then pass it back.
    Code (csharp):
    1. if (walking) {
    2.     transform.position = transform.position + Camera.main.transform.forward * .5f * Time.deltaTime;
    3.     Vector3 pos = transform.position;
    4.     pos.y = 0.5f;
    5.     transform.position = pos;
    6. }
    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs1612
     
    Bill_Martini and JoeStrout like this.
  3. linglonglinglong

    linglonglinglong

    Joined:
    Feb 26, 2018
    Posts:
    20
    Thank you very very much!!!