Skip to content

Instantly share code, notes, and snippets.

@AndySum
Created April 1, 2018 04:32
Show Gist options
  • Save AndySum/e4b31648658c55dade561cd8e29918f9 to your computer and use it in GitHub Desktop.
Save AndySum/e4b31648658c55dade561cd8e29918f9 to your computer and use it in GitHub Desktop.
//put into two monobehaviours in unity if you want to run it, and put AwakeChild on a gameobject.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AwakeBase : MonoBehaviour {
protected bool setup = false;
Transform thisWillBeNullInChild;
void Awake()
{
setup = true;
thisWillBeNullInChild = GetComponent<Transform>();
DoWork();
}
public virtual void DoWork()
{
//this is where you would put your overrideable setup code
Debug.Log("Base work. Okay to override this.");
}
}
//Class two, child
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AwakeChild : AwakeBase {
//The developer does not know that AwakeBase implements Awake,
//and so does not know that they should call base.Awake()
//comment out Awake or add base.Awake() to see how it works
void Awake()
{
if (setup)
{
Debug.Log("I am setup");
}
else
{
Debug.Log("I am not setup");
}
}
//but we want them to override DoSetup
//ideally they don't override Awake() above, and only use this DoWork method:
public override void DoWork ()
{
//now you can write code here that will be called
Debug.Log("Child work called in Awake");
}
//however we can't enforce that? (This is the problem I want to enforce or make the developer explicity use "new")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment