Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Inheritance with Prefabs Not Working

Discussion in 'Scripting' started by imgodot, Jul 5, 2014.

  1. imgodot

    imgodot

    Joined:
    Nov 29, 2013
    Posts:
    212
    Hello All,

    I am trying to create a base class that inherits from MonoBehaviour and then have ALL my other classes inherit from my base class.

    Problem: If I instantiate a prefab that has an attached script inheriting from my base class, it creates another instance of my base class. Therefore, every prefab I create has its own copy of the base class.

    Real Problem: I simply don't know what I'm doing.

    QUESTION: How do I create/use a base class that will be the same instance of the base class for all my instantiated prefabs?

    Much appreciated if someone can lift my ignorance.
    -- Paul

    ====== a rough idea of my existing class structure ======
    public class MyBaseClass : MonoBehaviour {
    public int counter = 0;​
    }

    public class FirstPrefab : MyBaseClass {
    void Start() {
    Debug.Log(base.counter++);​
    }​
    }

    public class SecondPrefab : MyBaseClass {
    void Start() {
    Debug.Log(base.counter++);​
    }​
    }
     
  2. BFGames

    BFGames

    Joined:
    Oct 2, 2012
    Posts:
    1,543
    Think you need to read up on inheritance and static variables if i understand your problem right :)
    (hint: static variables is shard among the instances)
     
  3. rrh

    rrh

    Joined:
    Jul 12, 2012
    Posts:
    331
    Yes, maybe you're unclear on something. Every time you instantiate a prefab, that's going to be a new instance by definition. That's what instantiate means, that it creates a new instance.

    So every instance of MyBaseClass will have its own instance of counter, and each will start at 0 and will then go up by 1 when the start function runs.

    BFGames might have figured out what you really intended? If you made counter a static variable then there would be only one counter variable shared throughout every instance of a MyBaseClass.