How to build up the class structure for an object

Hi!

So i have this character “Soldier” and this gameobject has a script called “Soldier”.
In this script i declare a set of variables for the class.

I also have another script on the gameobject called “SoldierMove” and this script/class inherits from the “Soldier” script/class.

However when i set a prefab for the “Soldier” classes variable “wayPointTarget”, i cant seem to access this in the “SoldierMove” script.

Also in the “Soldier” scipt when i set the variable currentTarget, in the script “SoldierMove” it stays null.

Isnt the “SoldierMove” script supposed to inherit the values from the “Soldier” script?

Here is some of the “Soldier” script:

using UnityEngine;
using System.Collections;

public class Soldier : MonoBehaviour {

	
	public Transform currentTarget;
	public GameObject wayPointTarget;

	// Use this for initialization
	void Awake() {
		currentTarget = GameObject.Find ("Target");
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}

And Here is the “SoldierMove” script:

using UnityEngine;
using System.Collections;

public class SoldierMove : Soldier {
	
	// Use this for initialization
	void Start () {
		Instantiate (wayPointTarget, Vector3(0, 0, 0), Quaternion(0, 0, 0));
	}
	
	// Update is called once per frame
	void Update () {
		Debug.Log (currentTarget.name);
	}
}

Note that these are not the actual scripts, but rather conceptual scripts meant to illustrate the problem.

Why i want to do all of this is so taht i dont have to have one large script (the “Soldier” script), but rather a set of smaller scripts, that each do a specific thing, like move, attack, find target and so on. And i want to access the variables easily, so if i for example set in the “FindTarget” script the “currentTarget” variable to be “Target”, then in the “Attack” script i want to access that variable and know what the target currently is.

So am i missunderstanding the inheritance system, or what am i doing wrong?

Thanks in advance!

When you have a gameobject with two scripts attached with it, each script is going be instantiated as a new object. The code will do new Soldier() and new SoldierMove() and attach those two instances to the gameobject. When you set something on one of them, the other one is not going to know about it because it’s a different instance (regardless of inheritance).

It’s perfectly acceptable to have multiple scripts in one gameobject because it gives you the ability to query the gameobject that the scripts are attached to for its components (i.e., other scripts), so from the SoldierMove script you can do GetComponent(), which will return the actual instance of the Soldier script. From that you can access the target variable and do what you need.