- Home /
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
Answer by Chikari · Feb 13, 2017 at 01:54 PM
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;
}
right but i have 1 question: if there will be 2 identical objects this variables can be store in same class (this storage class is attached to empty gameobject or its attached to the same object as those scripts) ? anyway thanks :D
You can use the same class prototype, but you have to create an individual object of type StorageClass within each object. Call storage = new StorageClass();
in the Start function of each object to create a new object.
but storage class is attached to other gameobject or to object with those scripts?
Yes they can be stored in the same class. In the example @Chikari gave, A and B are holding a reference to the same instance of the StorageClass
. In the example, A calls B.setStorageReference
to give it the same reference.
i am confused by this part
GetComponent < B > ().enabled = true;
GetComponent < B > ().setStorageReference(storage);
i tried to get access to scripts by this way with or without adding B script to object but it doesn't work.
You have to have the B script on the object already. If you want to add one programmatically: B compB = gameObject.AddComponent<B>();
still don't work this is the error: Expression denotes a method group', where a
variable', value' or
type' was expected