public class t1 : MonoBehaviour
{
public int i;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
i++;
}
}
---------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class t2 : MonoBehaviour
{
public t1 t;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Debug.Log(t.i);
}
}
But this doesn’t:
public class t2 : t1
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Debug.Log(i);
}
}
When you inherit from a class that inherits from mono behaviour, the mono functions of the base class are overridden by the mono functions of the new class. So if t2 inherits from t1 (which inherits from monobehaviour), only the mono functions on t2 are called (by default). t1 no longer has any mono functions (called automatically by Unity - you have to call them yourself).
To get around this, you may need to use a different method (instead of Update()), for t2 e.g. LateUpdate(). Inheriting from a base class shouldn’t really be done if the base class inherits from mono, for this confusing reason. @hasan061
Like @Llama_w_2Ls already explained, a single class can only have one version of a certain method. So Your T2 class has an Update method that hides the one your class has inherited from T1. Since they are private the method wouldn’t be visible in the derived class anyways. When you plan to use inheritance with MonoBehaviour base classes, you should always declare the Unity callbacks as protected and not private. That way the derived class can call the parent method if necessary / wanted
public class T1 : MonoBehaviour
{
public int i;
protected virtual void Update()
{
i++;
}
}
public class T2 : T1
{
protected override void Update()
{
base.Update(); // call the method of the base class
Debug.Log(i);
}
}
While in Unity it would not be necessary to declare the method as virtual, this is how proper inheritance work outside of Unity. In Unity you could omit the “virtual” in the base class and replace “override” with “new”. Though this only works because Unity directly calls the method on the actual class.