Access local method variable in derived class

Dear Community,

I have a class called BuildOption. In it I have a method called Build().

protected virtual void Build(Hex targetHex)
    {
        Actor instance = Instantiate(actorPrefab);
        instance.GetComponentInChildren<MeshRenderer>().material = SelectedMaterial;
        instance.MyHex = targetHex;
    }

This method instantiates a prefab called actorPrefab, changes the material of the instance and changes some Property called MyHex.

I have a child class called MonsterBuild which inherits from BuildOption. In the child class I wish to override the method Build and add some functionality. Specifically I would like to change another property of ‘instance’. However ‘instance’ is a local variable to the parent Build() method.

protected override void Build(Hex targetHex)
{
    base.Build(targetHex);
    instance.ID = Random.Range(1, 10); //this doesn't work because instance doesn't exist in this methods scope
}

Is there a possibility to access the variable ‘instance’ in the child class? Or is there another way for me to change a property on ‘instance’ in the child method?

Thank you.

I see several possibilities.

1. Declare the instance variable protected in your class so that your base class and derived class can access it.

2. Make the Build function return instance. If the callers does not use the returned instance, it’s not a problem

 // Base class
 protected virtual Actor Build(Hex targetHex)
 {
     Actor instance = Instantiate(actorPrefab);
     instance.GetComponentInChildren<MeshRenderer>().material = SelectedMaterial;
     instance.MyHex = targetHex;
     return instance;
 }

 // Derived class
 protected override Actor Build(Hex targetHex)
 {
     Actor instance = base.Build(targetHex);
     instance.ID = Random.Range(1, 10);
     return instance;
  }

3. Use an additional virtual method to do the job

 // Base class
 protected void Build(Hex targetHex) // Notice we have removed the virtual keyword here
 {
     Actor instance = Instantiate(actorPrefab);
     instance.GetComponentInChildren<MeshRenderer>().material = SelectedMaterial;
     instance.MyHex = targetHex;
     SetupActor( instance );
 }

 protected virtual void SetupActor( Actor instance )
 {
     // Do nothing, overriden in subclasses
 }

 // Derived class
 protected override void SetupActor(Actor instance)
 {
     instance.ID = Random.Range(1, 10);
  }

what if you declare the instance variable out side the build method in the parent class and make it public so all your child classes and methods will access it.