I’ve seen this question asked, and the answer seems to be that it can’t be done…but it’s such a common thing to do in other languages I’m surprised. So, maybe I’m misunderstanding something.
I’m creating a molecular simulation game. It will have lots of atoms with basically all the same functions, but needing different parameters.
It seems the best way to do this (and avoid necessary code duplications) is to write a general “nucleus.cs” script with the action methods, which access a “characteristics.cs” script to determine these parameters.
But there seems no way to attach different (unknown or differently named) scripts to the variable because of C#'s restrictive casting.
I.e… the plan:
(This script goes on ALL atoms)
public class NucleusScript : MonoBehaviour {
// External object references
public IdontKnowWhatToPutHere characteristics;
public void reactWithHydrogen(){
if (distance < characteristics.electronegativity){
// make boom and stuff
}
}//end class
(OxygenCharacteristic.cs)
public class OxygenCharacteristics : MonoBehaviour {
float ELECTRONEGATIVITY = 3.44;
public float electronegativity {
get {return ELECTRONEGATIVIY;}
SET {throw new error you can't do this yadda};
}
}//class
(NitrogenCharacteristic.cs)
public class NitrogenCharacteristic : MonoBehaviour {
float ELECTRONEGATIVITY = 3.04;
public float electronegativity {
get {return ELECTRONEGATIVIY;}
SET {throw new error you can't do this yadda};
}
)//class
Then, in unity editor, the nucleus script is dragged to ALL the different atom objects (I.e. Oxygen, Nitrogen, etc)…with this “characteristics” variable placeholder.
THEN, also in unity editor, the script “OxygenCharacteristic.cs” is dragged onto the “characteristics” placeholder within the nucleus script associated with Oxygen.
AND the “NitrogenCharacteristic.cs” script is dragged onto the “characteristics” spot for the nucleus script attached to the nitrogen object.
I hope this makes sense. It’s late.
I’m not locked into this solution. If there’s another way to accomplish this, please suggest it.
Thanks!