Home > Back-end >  Prefab instantiated as an object with my methods
Prefab instantiated as an object with my methods

Time:04-16

I have an idea that there must be a way to attach a class to a prefab - basically to add my own methods to the code. Then, when I instantiate my prefab in runtime I want it to be an instance of this class.

Now, I can attach a script to a prefab and it's Start and Update works, but my idea is something like this:

public class PowerupWidget : MonoBehaviour {
    void Start() {
        Debug.Log("PowerupWidget created!!!");
    }
    void SetTitle(string title) {
        // ... set the prefab's title widget text ...
    }
}

When I instantiate my prefab, the Start method is called. But the instance is of course the GameObject type.

// in my scene script:
// prefab is my PowerupWidget
GameObject p = Instantiate(prefab, transform.position, Quaternion.identity, this.transform);
// here p is GameObject of course

Is there a way how to get to the instance of the PowerupWidget class, or am I completely wrong in my assuptions?

CodePudding user response:

Unity using ECS, which means

  • Things are divided into entities and component, when entities are gameobject and components are classes that are attached to this script.

You just need to do this

PowerupWidget yourWidget = p.GetComponent<PowerupWidget>();
  • Related