PeterK
PeterK

Reputation: 4301

Why is Start running twice in this setup

I created a completely new project with the following scripts attached to an empty GameObject:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Parent : MonoBehaviour
{
    void Start()
    {
        print(">>>>>>>>>>>>> S T A R T <<<<<<<<<<<<<");
    }
}

and:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Child : Parent
{

}

Here is the result:

[07.07.55] >>>>>>>>>>>>> S T A R T <<<<<<<<<<<<<
UnityEngine.MonoBehaviour:print(Object)
[07.07.55] >>>>>>>>>>>>> S T A R T <<<<<<<<<<<<<
UnityEngine.MonoBehaviour:print(Object)

Why is Start executing twice in this setup?

Upvotes: 0

Views: 299

Answers (1)

MyBug18
MyBug18

Reputation: 2240

Since the given situation is super simple, there are some possibilities, I think.

  1. Actually, there are two gameobjects attatched with given script.

  2. You attatched each Parent and Child component seperately.

...both are not very recommended way to use unity.

When designing a MonoBehaviour-inheriting class which maybe inherited by other class, it's often to declare Unity event function with virtual keyword, like:

public class Parent : MonoBehaviour
{
    protected virtual void Start()
    {
        Debug.Log(">>>>>>>>>>>>> S T A R T <<<<<<<<<<<<<");
    }
}

public class Child : Parent
{
    protected override void Start()
    {
        base.Start();
        Debug.Log("This is Child!");
    }
}

And with gameobject attatched with Child, the console will write

>>>>>>>>>>>>> S T A R T <<<<<<<<<<<<<
This is Child!

But with Parent component, it will write only

>>>>>>>>>>>>> S T A R T <<<<<<<<<<<<<

Upvotes: 2

Related Questions