- Home /
C# Inheritance - Reference the INSTANCE of a variable, is it possible?
I've been digging around and have found many similar but not exactly matching results to this question, all of which have made this infinitely more confusing. Below is example mock-up code of what we're trying to do here. Please read the bottom paragraph for an explanation. Thank you!
Base.cs
using UnityEngine;
using System.Collections;
public class Base : MonoBehaviour {
public GameObject Chase;
void Update () {
Chase = GameObject.Find("Chase"); // Never GO.Find on Update, this is just a mock-up.
}
}
Race.cs
using UnityEngine;
using System.Collections;
public class Race : Base {
void Update () {
Debug.Log(Chase);
}
}
With that in-mind, is it possible to get the instance of a variable that we're inheriting from? The idea here is having a 'base' class that houses a couple variables that will be used across all scripts within the project. These variables are assigned during run-time, so we need to grab the Instance of them. However at this point, I am no longer sure if this is something inheritance will support. Statics don't seem like the way to go, and namespaces/interfaces are just as useless in this case scenario.
Answer by andrew-lukasik · Apr 17, 2016 at 11:16 AM
Singleton solution could look like this for example:
//add this class to your Chase gameObject and make sure it's in the Scene somewhere:
public class ChaseClass : MonoBehaviour {
private static ChaseClass _singleton;
public static ChaseClass singleton {
get {
return _singleton;
}
}
public static GameObject go {
get {
return _singleton.gameObject;
}
}
void Awake () {
//address singleton
if( _singleton==null ) {
_singleton = this;
}
else if( _singleton!=this ) {
Destroy( this.gameObject );
}
}
}
//this is how you will access this Chase gameobject from any class:
public class AnyClass : MonoBehaviour {
void Update () {
Debug.Log( ChaseClass.go );
}
}
Not as good but still working solution based on inheritance could look like this:
public class Base : $$anonymous$$onoBehaviour {
protected static GameObject Chase;
virtual protected void Awake () {
if( Chase==null ) {
Chase = GameObject.Find( "Chase" );
}
}
}
public class Race : Base {
override protected void Awake () {
base.Awake();//calls Awake() as defined in parent class:
Debug.Log( Chase );
}
void Update () {
Debug.Log( Chase );
}
}
Thanks a lot for the help! While I'm sure the code within the first post will help someone out there, it doesn't quite help me in this scenario. The variable(s) we're trying to use in the 'base' class could be anything, from a GameObject to an int/bool. Any variables that will be used across all scripts within the project, which is exactly why we need to grab the instance themselves. With that said, I'll definitely give your seconds script a try when I get the chance!