How to change a customScript variable into another customScript? I don't know how to word it.

Okay, basically I want to have a var called script; however, I want to be able to change it between different variable Types.

P.S: Please ignore the obvious resource-intensive stuff, I’m too lazy to actually create a full script as an example.


NOT this:

var otherVar = 3;
var script = "";
print(script);

script = otherVar.ToString();
print(script);         // would print 3

// do other stuff with script variable

script = (2.5f).ToString();
print(script);         // script would print 2.5f

But this:

var script;
if ( exObj.GetComponent<baseEnemy>() ) {
    script = exObj.GetComponent<baseEnemy>(); 
    script.takeEnemyDamage(damage);
}
else if ( exObj.GetComponent<baseBoss> ){
    script = exObj.GetComponent<baseBoss>();
    script.takeBossDamage(damage * .5f)
}

So the problem here is that “Implicitly-typed variables must be initialized” and you can’t initialize it until you know the type. For the example you showed I would use interfaces instead.


Somewhere in your codebase:

public interface IDamageTaker
{
    public void TakeDamage(float dmg);
}

Where you access the scripts:

 IDamageTaker script;
 if ( exObj.GetComponent<baseEnemy>() ) {
     script = exObj.GetComponent<baseEnemy>(); 
     script.takeEnemyDamage(damage);
 }
 else if ( exObj.GetComponent<baseBoss> ){
     script = exObj.GetComponent<baseBoss>();
     script.takeBossDamage(damage * .5f)
 }

In the scripts:

public class baseBoss : MonoBehaviour,IDamageTaker
{
    public void TakeDamage(float dmg)
    {
        //Custom implementation
    }
}

This way you can only access the properties and methods declared in the interface but I do belive it is the best way to go. To my knowledge there is now way to have a type-fluid variable in c#.