C# inheritance problem

I am stuck on class inheritance. Probably someone could shed some light:

My game uses different “boxes”. Each different box gameobject has one script attached to control it. The scripts of all boxes are inherited from one common class so that I can control all different boxes in my gamescript without the need to know each box-class by itself.

Common class:

public class boxClass : MonoBehaviour {
	public string p_name;
}

Inherited box (attached to a gameobject):

public class box10 : boxClass {
	void Awake () {	
		p_name= "funkeybox bana muffin ninja";
	}
}

My gamescript (the gameobject of which the "box10 " script is a part of is attached to the public member shown below):

public class myGameScript : MonoBehaviour {
	public boxClass p_script_box10;
	//public box10 p_script_box10;    Alternative. Doesn't work aswell.

	void Start () {
		Debug.Log(p_script_box10.p_name);
	}
}

The code runs without errors but the string shows up empty. Why?

because you declare p_script_box10 as a boxClass type, and not as a box10 type…

Already tried that. Makes no difference. Code runs fine both ways but the result is an empty string.

… where are you creating the box object?

In the editor. The gameobject is already in the hierarchy when the game starts.

Ah I got it. The gameobject exists but was inactive so that it doesn’t show up too early. Interesting. That means setting variables of scripts attached to disabled gameobjects are just discarded? Would be pretty stupid if you could only change/access the variables of a gameobject if its active… you might want to change it before activating.

What is the proper method of “hiding” a gameobject temporarily without crippling your code possibilities?
What are the rules for reading/writing to variables in scripts attached to disabled gameobjects?

If the GameObject is disabled via the Editor then Awake() won’t be called on it when the scene is loaded. You can either enable it in the Editor and then call SetActive(false) in Awake after you set your variables or set your variables in OnEnable().

The documentation is not clear and I can’t remember off the top of my head but you may run into issues using GetComponent if the entire hierarchy is disabled. For example - GetComponentsInChildren won’t work and the docs are explicit about that but it’s not consistent. You can, for example. enumerate a Transform of a disabled GameObject.

Interesting. Thank you!

My tests show that both Start() and Awake() will be called as soon as the GameObject is SetActive(true) at runtime. So that gives me multiple ways to handle this.

Here’s a picture of the MonoBehaviour lifetime cycle. I found it on the net (but I don’t remember where though :frowning: )

It can be useful on the desk :wink:

This is a nice and clean piece of information! Very helpful indeed. Thank you!