'Prefab instantiated as an object with my methods
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?
Solution 1:[1]
Structure in unity :
- Things are divided into entities and component, when entities are gameobject and components are classes(Script) that are attached to this gameobject.
You just need to do this
PowerupWidget yourWidget = p.GetComponent<PowerupWidget>();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
