0
\$\begingroup\$

I am using 3 classes:

  1. EnemyBullet : MonoBehavior

  2. EnemyBulletType1 : EnemyBullet

EnemyBullet Class:

void FixedUpdate(){ 
    this.gameObject.transform.rotation = Quaternion.Euler (new Vector3 (0,0,90));
}

EnemyBulletType1 Class:

override void FixedUpdate() {
    base.FixedUpdate ();
    //Do something else here
}

The reason is I'll have many EnemyBulletType classes and I want them all to do a common thing and then do something on their own.

Question: This code isn't working: Error: virtual or abstract members cannot be private How is FixedUpdate() defined in the MonoBehviour and how to change it to help my usecase?

\$\endgroup\$
3
  • \$\begingroup\$ Can you give some examples of the different behaviours you want to create this way? There might be more flexible ways to do it. Particularly in Unity, when you run into snags with inheritance following the principal of Composition Over Inheritance helps de-thorn the issue. \$\endgroup\$ Commented Apr 5, 2018 at 14:08
  • \$\begingroup\$ @DMGregory although the question has been resolved, That seems very interesting to me! Do you mean to say instead of inheriting from one base class; create isolated functionalites and apply them to each enemy type individually? \$\endgroup\$ Commented Apr 5, 2018 at 15:26
  • \$\begingroup\$ Yes. I find it's a pattern that works well in Unity projects I've built or contributed to. That can be a matter of personal preference through, not necessarily a "best practice" that every game should follow. But keep it in mind the next time you reach for polymorphism to accomplish variation in game content — composition is often easier to scale and remix as the game evolves. \$\endgroup\$ Commented Apr 5, 2018 at 17:15

1 Answer 1

1
\$\begingroup\$

As indicated by the compiler, the function can't be private.

In C#, the default visibility is private. When you want to create virtual functions which can be overriden in sub-classes, you have to explicitely set the visibility to public (not advised here, because it's a MonoBehaviour function that should not be called by anything but Unity itself) or protected:

See MSDN documentation : https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual

You cannot use the virtual modifier with the static, abstract, private, or override modifiers.

Indeed, if you want your subclass to know the function to override, the latter must be visible by your subclass (which is not possible if the function is private)


EnemyBullet Class:

protected virtual void FixedUpdate(){ 
    this.gameObject.transform.rotation = Quaternion.Euler (new Vector3 (0,0,90));
}

EnemyBulletType1 Class:

protected override void FixedUpdate() {
    base.FixedUpdate ();
    //Do something else here
}
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.