changin functionality of gameobject/script without loosing variables C#

How to change a script/functionality of gameobject without loosing a variables in that script? I want to do something like this: if object has less then 0 hp it becomes our and if so it must have functionality like our objects but i didn’t want to just instantiate another prefab but only change functionality. How can I do this? Maybe something with classes?
btw. sorry for my english

Store your “global” variables in another class and pass the reference to your second script before switching functionality (=enabling the second behaviour, disabling the first behaviour).

public class A: MonoBehaviour {
 StorageClass storage;
 
 public void doSomething() {
  storage.thisVar = 5;
 }
 
 public void switchFunctionality() {
  GetComponent < B > ().enabled = true;
  GetComponent < B > ().setStorageReference(storage);
  this.enabled = false;
 }
}

public class B: MonoBehaviour {
 StorageClass myStorageClass;
 
 public void setStorageReference(StorageClass storage) {
  myStorageClass = storage;
 }

 void doSomething() {
  Debug.Log(storage.thisVar); //will be 5 if not changed elsewhere
 }
}

public class StorageClass {
 public int thisVar;
 public float thatVar;
 public string anotherVar;
}