Hierarchy scrpit variables

Hi, I wrote a script in C# which is like this:

Script1{

public GameObect obj1;

public Transform tra;

other variables…

and then there are some functions which use these variables

}

There is also another Script which inerits from Script1

Script2: Script1{

void Update(){

Here I use the functions and variables defined in Script1

}

}

The public variables in Script1 are defined in the Inspector

But when i press play on Unity, an error occurs…

It says me that i have to define the variables also in Script2… But why i have to do it ? I think it has no sense… because if the variables of Script2 are the same of Script1 i don’t have to define them again…

What i have to do ?

Thank you so much, Alessio:)

Hi there,

whilst you might define public variables in the editor, what you’re really doing is assigning values to variables held in that instance of a script, rather than all instances of the script in general.

Therefore, when you inherit from Script1, you’re inheriting the structure defined in your code (e.g. it knows that it should hold a GameObject called obj1), but not the assignments made in the editor (e.g. it knows that obj1 should be a specific object in the scene) - these are ‘local changes’ made to that instance of a script.

How would you make this work? Well, it really depends what you want to do, and why you want to do it. If you want value assignments to be generic, then you need to avoid making them in the editor. I.e. instead of writing:

public GameObect obj1; // Assign in editor
public Transform tra;  // Assign in editor

you could do:

public GameObect obj1;
public Transform tra;

Start(){
obj1 = GameObject.FindGameObjectWithTag("SomeTag"); // Define SomeTag and attach it to the relevant GameObject in the inspector.

tra = GameObject.FindGameObjectWithTag("SomeOtherTag").GetComponent<Transform>(); // Define SomeOtherTag and attach it to the relevant GameObject in the inspector.
}

This way, variable assignment would be defined in the scructure of Script1 and inherited by Script2. However, this is a workaround. I’d recommend (in the long term) refactoring your code so that you can take more full advantage of the features that Unity affords - such as assigning variables in the editor.