'get' and 'set' question

Hello. I just finished watching all 49 tutorials in the Unity scripting basic section. In the tutorials it made sense. But I was looking at someone else’s code and It was used differently and I don’t quite understand what’s going on.

There are two classes. The first one is a base class, and the second one inherits it.

public abstract class BaseClass : MonoBehaviour
{
public GameObject _MyTarget;
public abstract GameObject MyTarget {get; set;}
}

public class MainClass : BaseClass
{
public override GameObject MyTarget
{
get { return _MyTarget; }
set
{
if (value != _MyTarget)
{
_MyTarget = value;
targetRigidbody = _MyTarget ? _target.GetComponent () : null;
}
}
}
}

I’m trying to merge the two scripts together by getting rid of BaseClass and move ‘_MyTarget’ and ‘MyTarget’ to ‘MainClass’ but I can’t seem to understand what they are doing in the MainClass. Any help would be really appreciated. Thank you!

Use code tags:

As for the code…

Umm… that’s some poorly written code. And a lot of it doesn’t actually do what I believe the coder intends it to do.

Anyways, a getter/setter/ is a C# mechanism to make a pair of functions (a get, and a set) to look and act like a ‘Field’ (a variable defined on the class itself, in this case ‘_MyTarget’). This is called get/set pair is referred to as a ‘Property’.

In MainClass the property is being used to perform some validation every time the property is set (this is at runtime, and not in the inspector). It’s validation sets a second variable named ‘targetRigidbody’ to a Rigidbody found in the new target.

A cleaned up version, with classes merged, would look something like this:

public class MainClass : MonoBehaviour
{

    [SerializeField()]
    private GameObject _myTarget;
   
    public GameObject MyTarget
    {
        get { return _myTarget; }
        set
        {
            if(value != _myTarget)
            {
                _myTarget = value;
                //honestly I don't know where 'targetRigidbody' is defined, it's nowhere in your example
                targetRigidboy = _myTarget ? _myTarget.GetComponent<RigidBody>() : null;
            }
        }
    }

}

Thank you so much! and super sorry about not using code tags. I’ll get into that practice immediately.

MUCH appreciate it, and the code makes a lot more sense now, and the cleaned up version looks much better. I like have code in one spot if it’s related enough.

The rigidbody is in the code later, but I wasn’t particularly confused about it, sorry if it just confused things by leaving it in there. I was more focused on the get and set part of the code.

Anyway, thanks again! Total life saver-