Hi ! I want to do something like that:
class A
{
public void A1()
{
B(); // I can't do that
}
}
class Tester : MonoBehaviour
{
A a;
void Start()
{
a = new A();
a.A1();
}
void B()
{
Debug.Log("nice");
}
}
How I can achieve that? Putting the same method B in class A just doesn’t seem like right way to do that.
class A
{
public void A1()
{
Tester b = new Tester();
b.B();
}
}
And don’t forget to make your B() function public.
your going to want to google whats called inheritence.
the jist of the answer is
Class A : monobehavior
{
Public void AI();
}
Class B : A
{
}
B Bexample;
Void update()
{
B.AI; // this is valid, B inherits from A, it is a kind of a and has all A's functions etc.
}
inheritence allows you to have a common base class of something and distinct children and they all have common features.
weapons for example
This is pretty code filled but basically you have this parent class, that’s BaseMeleeWeapon, it has a function called attack. Now Sword and Spear are child classes, they inherit from it. Because of that a sword IS a BaseMeleeWeapon, a Spear IS a BaseMeleeWeapon. a sword is not a spear however or the other way around. But this means that if you put common stuff in it and in code instead of storing a spear as a spear you store it as a basemeleeweapon and refer to it that way, you can easily swap it out for a spear and all the code still works because both are of type basemeleeweapon.
A bool for example is actually just an integer and you can in fact treat a bool like an int, because it is one.
bool test;
int othertest;
othertest = test;
works
Because a bool inherits from int.
BaseMeleeWeapon : monobehavior
{
virtual void Attack();
}
Sword : BaseMeleeWeapon
{
Attack()
{
//insert here how a sword attacks
}
}
Spear : BaseMeleeWeapon
{
Attack()
{
//insert here the code for how a spear attacks
}
}
BaseSoldier : Monobehavior
{
BaseMeleeWeapon MeleeWeapon;
BaseMeleeWeapon SecondaryWeapon;
BaseMeleeWeapon EquippedWeapon;
void Start()
{
MeleeWeapon = new Sword();
SecondaryWeapon = new Spear();
EquippedWeapon = MeleeWeapon;
}
void EquipSecondary()
{
EquippedWeapon = SecondaryWeapon()
}
void WeaponAttack()
{
EquippedWeapon.Attack()
}
This code allows you to have multiple weapons, swap between them, have the right attack code executed and it’s all fine, you can easily add a third weapon with it’s own unique attacks or fourth and no change needs to be made to existing code, you just need new code really.